<p>My question concerns c# and how to access Static members ... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code:</p>
<pre><code>Class test&lt;T&gt;{
     int method1(Obj Parameter1){
         //in here I want to do something which I would explain as
         T.TryParse(Parameter1);

         //my problem is that it does not work ... I get an error.
         //just to explain: if I declare test&lt;int&gt; (with type Integer)
         //I want my sample code to call int.TryParse(). If it were String
         //it should have been String.TryParse()
     }
}
</code></pre>
<p>So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you!</p>
<hr />
<p>Edit: Thank you all for your answers!</p>
<p>Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch.</p>
<p>This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way ... maybe in the next language I learn)</p>
<hr />
<p>Though if you have some other suggestion I am still waiting (and willing to participate)</p>

[{'answer_id': 19862, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 3, 'selected': False, 'text': '<p>The problem is that TryParse isn\'t defined on an interface or base class anywhere, so you can\'t make an assumption that the type passed into your class will have that function.  Unless you can contrain T in some way, you\'ll run into this a lot.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/d5x73970.aspx" rel="noreferrer" title="C# Programming Guide (MSDN)">Constraints on Type Parameters</a></p>\n'}, {'answer_id': 19863, 'author': 'svrist', 'author_id': 86, 'author_profile': 'https://Stackoverflow.com/users/86', 'pm_score': 0, 'selected': False, 'text': '<p>You probably cant do it.</p>\n\n<p>First of all if it should be possible you would need a tighter bound on T so the typechecker could be sure that all possible substitutions for T actually had a static method called TryParse.</p>\n'}, {'answer_id': 19867, 'author': 'Nick Berardi', 'author_id': 17, 'author_profile': 'https://Stackoverflow.com/users/17', 'pm_score': -1, 'selected': False, 'text': '<p>That is not how statics work.  You have to think of statics as sort of in a Global class even if they are are spread across a whole bunch of types.  My recommendation is to make it a property inside the T instance that can access the necessary static method.</p>\n\n<p>Also T is an actual instance of something, and just like any other instance you are not able to access the statics for that type, through the instantiated value.  Here is an example of what to do:</p>\n\n<pre><code>class a {\n    static StaticMethod1 ()\n    virtual Method1 ()\n}\n\nclass b : a {\n    override Method1 () return StaticMethod1()\n}\n\nclass c : a {\n    override Method1 () return "XYZ"\n}\n\nclass generic&lt;T&gt; \n    where T : a {\n    void DoSomething () T.Method1()\n}\n</code></pre>\n'}, {'answer_id': 19885, 'author': 'samjudson', 'author_id': 1908, 'author_profile': 'https://Stackoverflow.com/users/1908', 'pm_score': 2, 'selected': False, 'text': '<p>To access a member of a specific class or interface you need to use the Where keyword and specify the interface or base class that has the method.</p>\n\n<p>In the above instance TryParse does not come from an interface or base class, so what you are trying to do above is not possible. Best just use Convert.ChangeType and a try/catch statement.</p>\n\n<pre><code>class test&lt;T&gt;\n{\n    T Method(object P)\n    {\n       try {\n           return (T)Convert.ChangeType(P, typeof(T));\n       } catch(Exception e) {\n           return null;\n       }\n    }\n}\n</code></pre>\n'}, {'answer_id': 19887, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 0, 'selected': False, 'text': '<p>You may want to read my previous post on <a href="https://stackoverflow.com/questions/8941/generic-type-checking">limiting generic types to primitives</a>. This may give you some pointers in limiting the type that can be passed to the generic (since <em>TypeParse</em> is obviously only available to a set number of primitives ( <em>string.TryParse</em> obviously being the exception, which doesn\'t make sense).</p>\n\n<p>Once you have more of a handle on the type, you can then work on trying to parse it. You may need a bit of an ugly switch in there (to call the correct <em>TryParse</em> ) but I think you can achieve the desired functionality.</p>\n\n<p>If you need me to explain any of the above further, then please ask :)</p>\n'}, {'answer_id': 19911, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 1, 'selected': False, 'text': "<p>Do you mean to do something like this:</p>\n\n<pre><code>Class test&lt;T&gt;\n{\n     T method1(object Parameter1){\n\n         if( Parameter1 is T ) \n         {\n              T value = (T) Parameter1;\n             //do something with value\n             return value;\n         }\n         else\n         {\n             //Parameter1 is not a T\n             return default(T); //or throw exception\n         }\n     }\n}\n</code></pre>\n\n<p>Unfortunately you can't check for the TryParse pattern as it is static - which unfortunately means that it isn't particularly well suited to generics.</p>\n"}, {'answer_id': 19982, 'author': 'Dan Herbert', 'author_id': 392, 'author_profile': 'https://Stackoverflow.com/users/392', 'pm_score': 1, 'selected': False, 'text': "<p>The only way to do exactly what you're looking for would be to use reflection to check if the method exists for T.</p>\n\n<p>Another option is to ensure that the object you send in is a convertible object by restraining the type to IConvertible (all primitive types implement IConvertible). This would allow you to convert your parameter to the given type very flexibly.</p>\n\n<pre><code>Class test&lt;T&gt;\n{\n    int method1(IConvertible Parameter1){\n\n        IFormatProvider provider = System.Globalization.CultureInfo.CurrentCulture.GetFormat(typeof(T));\n\n        T temp = Parameter1.ToType(typeof(T), provider);\n    }\n}\n</code></pre>\n\n<p>You could also do a variation on this by using an 'object' type instead like you had originally.</p>\n\n<pre><code>Class test&lt;T&gt;\n{\n    int method1(object Parameter1){\n\n        if(Parameter1 is IConvertible) {\n\n            IFormatProvider provider = System.Globalization.CultureInfo.CurrentCulture.GetFormat(typeof(T));\n\n            T temp = Parameter1.ToType(typeof(T), provider);\n\n        } else {\n           // Do something else\n        }\n    }\n}\n</code></pre>\n"}, {'answer_id': 20010, 'author': 'Weeble', 'author_id': 2283, 'author_profile': 'https://Stackoverflow.com/users/2283', 'pm_score': 2, 'selected': False, 'text': '<p>Short answer, you can\'t.</p>\n\n<p>Long answer, you can cheat:</p>\n\n<pre><code>public class Example\n{\n    internal static class Support\n    {\n        private delegate bool GenericParser&lt;T&gt;(string s, out T o);\n        private static Dictionary&lt;Type, object&gt; parsers =\n            MakeStandardParsers();\n        private static Dictionary&lt;Type, object&gt; MakeStandardParsers()\n        {\n            Dictionary&lt;Type, object&gt; d = new Dictionary&lt;Type, object&gt;();\n            // You need to add an entry for every type you want to cope with.\n            d[typeof(int)] = new GenericParser&lt;int&gt;(int.TryParse);\n            d[typeof(long)] = new GenericParser&lt;long&gt;(long.TryParse);\n            d[typeof(float)] = new GenericParser&lt;float&gt;(float.TryParse);\n            return d;\n        }\n        public static bool TryParse&lt;T&gt;(string s, out T result)\n        {\n            return ((GenericParser&lt;T&gt;)parsers[typeof(T)])(s, out result);\n        }\n    }\n    public class Test&lt;T&gt;\n    {\n        public static T method1(string s)\n        {\n            T value;\n            bool success = Support.TryParse(s, out value);\n            return value;\n        }\n    }\n    public static void Main()\n    {\n        Console.WriteLine(Test&lt;int&gt;.method1("23"));\n        Console.WriteLine(Test&lt;float&gt;.method1("23.4"));\n        Console.WriteLine(Test&lt;long&gt;.method1("99999999999999"));\n        Console.ReadLine();\n    }\n}\n</code></pre>\n\n<p>I made a static dictionary holding a delegate for the TryParse method of every type I might want to use. I then wrote a generic method to look up the dictionary and pass on the call to the appropriate delegate. Since every delegate has a different type, I just store them as object references and cast them back to the appropriate generic type when I retrieve them. Note that for the sake of a simple example I have omitted error checking, such as to check whether we have an entry in the dictionary for the given type.</p>\n'}, {'answer_id': 20053, 'author': 'niklasfi', 'author_id': 2275, 'author_profile': 'https://Stackoverflow.com/users/2275', 'pm_score': 1, 'selected': False, 'text': '<p>Ok guys: Thanks for all the fish. Now with your answers and my research (especially the article on <a href="https://stackoverflow.com/questions/8941/generic-type-checking">limiting generic types to primitives</a>) I will present you my solution.</p>\n\n<pre><code>Class a&lt;T&gt;{\n    private void checkWetherTypeIsOK()\n    {\n        if (T is int || T is float //|| ... any other types you want to be allowed){\n            return true;\n        }\n        else {\n            throw new exception();\n        }\n    }\n    public static a(){\n        ccheckWetherTypeIsOK();\n    }\n}\n</code></pre>\n'}, {'answer_id': 20139, 'author': 'Timbo', 'author_id': 1810, 'author_profile': 'https://Stackoverflow.com/users/1810', 'pm_score': 3, 'selected': True, 'text': '<p>One more way to do it, this time some reflection in the mix:</p>\n\n<pre><code>static class Parser\n{\n    public static bool TryParse&lt;TType&gt;( string str, out TType x )\n    {\n        // Get the type on that TryParse shall be called\n        Type objType = typeof( TType );\n\n        // Enumerate the methods of TType\n        foreach( MethodInfo mi in objType.GetMethods() )\n        {\n            if( mi.Name == "TryParse" )\n            {\n                // We found a TryParse method, check for the 2-parameter-signature\n                ParameterInfo[] pi = mi.GetParameters();\n                if( pi.Length == 2 ) // Find TryParse( String, TType )\n                {\n                    // Build a parameter list for the call\n                    object[] paramList = new object[2] { str, default( TType ) };\n\n                    // Invoke the static method\n                    object ret = objType.InvokeMember( "TryParse", BindingFlags.InvokeMethod, null, null, paramList );\n\n                    // Get the output value from the parameter list\n                    x = (TType)paramList[1];\n                    return (bool)ret;\n                }\n            }\n        }\n\n        // Maybe we should throw an exception here, because we were unable to find the TryParse\n        // method; this is not just a unable-to-parse error.\n\n        x = default( TType );\n        return false;\n    }\n}\n</code></pre>\n\n<p>The next step would be trying to implement</p>\n\n<pre><code>public static TRet CallStaticMethod&lt;TRet&gt;( object obj, string methodName, params object[] args );\n</code></pre>\n\n<p>With full parameter type matching etc.</p>\n'}, {'answer_id': 1138729, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Best code: restrict T to ValueType this way:</p>\n\n<pre><code>class test1&lt;T&gt; where T: struct\n</code></pre>\n\n<p>A "struct" here means a value type.\nString is a class, not a value type.\nint, float, Enums are all value types.</p>\n\n<p>btw the compiler does not accept to call static methods or access static members on \'type parameters\' like in the following example which will not compile :(</p>\n\n<pre><code>class MyStatic { public static int MyValue=0; }\nclass Test&lt;T&gt; where T: MyStatic\n{\n    public void TheTest() { T.MyValue++; }\n}\n</code></pre>\n\n<p>=> Error    1   \'T\' is a \'type parameter\', which is not valid in the given context</p>\n\n<p>SL.</p>\n'}, {'answer_id': 10590634, 'author': 'Amir Abiri', 'author_id': 800334, 'author_profile': 'https://Stackoverflow.com/users/800334', 'pm_score': 2, 'selected': False, 'text': '<p>This isn\'t really a solution, but in certain scenarios it could be a good alternative: We can pass an additional delegate to the generic method.</p>\n\n<p>To clarify what I mean, let\'s use an example. Let\'s say we have some generic factory method, that should create an instance of T, and we want it to then call another method, for notification or additional initialization.</p>\n\n<p>Consider the following simple class:</p>\n\n<pre><code>public class Example\n{\n    // ...\n\n    public static void PostInitCallback(Example example)\n    {\n        // Do something with the object...\n    }\n}\n</code></pre>\n\n<p>And the following static method:</p>\n\n<pre><code>public static T CreateAndInit&lt;T&gt;() where T : new()\n{\n    var t = new T();\n    // Some initialization code...\n    return t;\n}\n</code></pre>\n\n<p>So right now we would have to do:</p>\n\n<pre><code>var example = CreateAndInit&lt;Example&gt;();\nExample.PostInitCallback(example);\n</code></pre>\n\n<p>However, we could change our method to take an additional delegate:</p>\n\n<pre><code>public delegate void PostInitCallback&lt;T&gt;(T t);\npublic static T CreateAndInit&lt;T&gt;(PostInitCallback&lt;T&gt; callback) where T : new()\n{\n    var t = new T();\n    // Some initialization code...\n    callback(t);\n    return t;\n}\n</code></pre>\n\n<p>And now we can change the call to:</p>\n\n<pre><code>var example = CreateAndInit&lt;Example&gt;(Example.PostInitCallback);\n</code></pre>\n\n<p>Obviously this is only useful in very specific scenarios. But this is the cleanest solution in the sense that we get compile time safety, there is no "hacking" involved, and the code is dead simple.</p>\n'}]
['https://Stackoverflow.com/questions/19843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2275/']