Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Short answer, you can't.</p> <p>Long answer, you can cheat:</p> <pre><code>public class Example { internal static class Support { private delegate bool GenericParser&lt;T&gt;(string s, out T o); private static Dictionary&lt;Type, object&gt; parsers = MakeStandardParsers(); private static Dictionary&lt;Type, object&gt; MakeStandardParsers() { Dictionary&lt;Type, object&gt; d = new Dictionary&lt;Type, object&gt;(); // You need to add an entry for every type you want to cope with. d[typeof(int)] = new GenericParser&lt;int&gt;(int.TryParse); d[typeof(long)] = new GenericParser&lt;long&gt;(long.TryParse); d[typeof(float)] = new GenericParser&lt;float&gt;(float.TryParse); return d; } public static bool TryParse&lt;T&gt;(string s, out T result) { return ((GenericParser&lt;T&gt;)parsers[typeof(T)])(s, out result); } } public class Test&lt;T&gt; { public static T method1(string s) { T value; bool success = Support.TryParse(s, out value); return value; } } public static void Main() { Console.WriteLine(Test&lt;int&gt;.method1("23")); Console.WriteLine(Test&lt;float&gt;.method1("23.4")); Console.WriteLine(Test&lt;long&gt;.method1("99999999999999")); Console.ReadLine(); } } </code></pre> <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>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload