Note that there are some explanatory texts on larger screens.

plurals
  1. POInvoke generic method with the generic type from a System.Type
    primarykey
    data
    text
    <p>below is a code example and the question, please note that I can NOT use C# 4.0 and the dynamic keyword.</p> <pre><code>static class TestClass { static void Main(string[] args) { Object o = "Previous value"; Test(ref o); Trace.WriteLine(o); } static public void Test&lt;T&gt;(ref T obj) { // The goal is to somehow invoke Test2 with the real type of obj, i.e the type in obj.GetType() // 1st try: Test2(ref obj); // This doesn't work because the type in Test2 will be the same as T here. // 2nd try: MethodInfo mi = typeof(TestClass).GetMethod("Test2"); mi = mi.MakeGenericMethod(new Type[] { obj.GetType() }); mi.Invoke(null, new Object[] { obj }); // obj is no longer by reference so we need to store the object array and copy back the result after the call // 3rd try, successful implementation by the smartest mind of stack overflow :) } static public void Test2&lt;T&gt;(ref T s) { if (typeof(T) == typeof(String)) { s = (T)(Object)"Hello world!"; } } } </code></pre> <p>I also tried some more methods using Delegate.CreateDelegate but without any luck. Is this at all possible?</p> <p>Edit: I'm not afraid of using a dynamic method (and MSIL assembler) but my knowledge in this area is very limited.</p> <p>Edit2: Here's an example that is closer to what I really trying to do:</p> <pre><code>public static class TypeHandler&lt;T&gt; { public delegate void ProcessDelegate(ref T value); public static readonly ProcessDelegate Process = Init(); private static ProcessDelegate Init() { // Do lot's of magic stuff and returns a suitable delegate depending on the type return null; } } static class TestClass { static public void Main(string[] args) { Object o = "Previous value"; Test(ref o); Trace.WriteLine(o); } static public void Test&lt;T&gt;(ref T obj) { if (obj is T) { // Optimized, common case TypeHandler&lt;T&gt;.Process(ref obj); return; } Type t = obj.GetType(); // How to call the delegate found in TypeHandler&lt;t&gt;.Process ? (I can get delegate but I can't call it). } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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