17 September 2007

Dynamically calling generic methods

Generic methods are very useful in building OO applications. Last time while factoring my old code I found some problems to invoke a method with generic type. So when I found this solution I decided to share with you. This sample is very easy to implement in many ways but my point is to show you how to use method with dynamical type.

In example I have a class Display.

public class Display

{

public string display(T value)

{

return string.Format("value: {0} type: {1}", value, typeof(T).Name);

}

}


Now I would like to invoke the "Display" method with variable type i.e. int, string, double and so on. The easiest way is replacing i.e. T with int.

[TestFixture]

public class DisplayTest

{

[Test]

public void Display_display_Test()

{

Display d = new Display();

string result = d.display<int>(100);

Assert.AreEqual("value: 100 type: Int32", result);

}

}


I know that is now correct answer because I have to know which type is going to be used. The right answer it is an example below.

[TestFixture]

public class DisplayTest

{

[Test]

public void Display_display_Test()

{

Display d = new Display();

int i = 100;

MethodInfo mi = typeof(Display).GetMethod("display");

MethodInfo miGeneric = mi.MakeGenericMethod(i.GetType());

string result = (string)miGeneric.Invoke(d, new object[] { i });

Assert.AreEqual("value: 100 type: Int32", result);

}

}

0 Comments:

Post a Comment

<< Home