Sunday, May 2, 2010

Sample Code for Dynamic Type in C#

Invoking a method using reflection is done by passing a string to InvokeMember (or whatever the thing is called).
Now the Dynamic makes it easy:

Below is the Sample Example of Dynamic

public partial class SampleForm : Form
{
public SampleForm()
{
InitializeComponent();
}

private void ShowResult_Click(object sender, EventArgs e)
{

Calc OrgCal = new Calc();
var Orgresult = OrgCal.Add(10,12);

Object objCal = new Calc();
Type CalType = typeof(Calc);
object objResult = CalType.InvokeMember("Add",System.Reflection.BindingFlags.InvokeMethod ,null,objCal, new Object[]{10,12});

dynamic dynCal= new Calc();
var dynResult = dynCal.Add(10,12);

}
}

class Calc
{

public int Add(int a, int b)
{
return a+b;
}

}


MSDN Help

http://msdn.microsoft.com/en-us/library/dd264736.aspx