RSS

Reflection Examples in C#

Fri, Mar 13, 2009

Programming, Tutorials

Following example demonstrate about loading assembly dynamically, creating instance, invoking method and getting/setting property value.

Creating instance from assembly (in project References)
Following example creates objects of DateTime class (this is from system assembly).

DateTime dt = (DateTime)Activator.CreateInstance(typeof(DateTime));
DateTime dt = (DateTime)Activator.CreateInstance(typeof(DateTime),
                                                       new object[] { 2009, 10, 9 });

Creating instance (with dynamically loaded assembly)
sample MyCalculator class

namespace MyCalc
{
    public class MyCalculator
    {
        public MyCalculator() {}
        public double Number { get;set;}
        public void Clear() {}
        private void DoClear() {}
        public double Add(double number) {}
        public static double Pi {}
        public static double GetPi() {}
    }
}

Various example or using reflection with MyCalc.dll assembly
Loading assembly from MyCalc.dll dynamically

Assembly myAssembly = Assembly.LoadFile(@"c:\MyCalc.dll");

Getting type of MyCalculator class

Type type = myAssembly.GetType("MyCalc.MyCalculator");

Creating instance of MyCalculator

object myCalcInstance = Activator.CreateInstance(type);

Getting property info

PropertyInfo myPropertyInfo = type.GetProperty("Number");

Getting property value

double value = (double)myPropertyInfo.GetValue(myCalcInstance, null);

Setting property value

myPropertyInfo.SetValue(myCalcInstance, 10.0, null);

Getting static property info

PropertyInfo piPropertyInfo = type.GetProperty("Pi");

Getting value from static property

double piValue = (double)piPropertyInfo.GetValue(null, null);

Invoking public instance method

type.InvokeMember("Clear",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
    null, myCalcInstance, null);

Invoking private instance method

type.InvokeMember("DoClear",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
    null, myCalcInstance, null);

Another public instance method

double value = (double)type.InvokeMember("Add",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
    null, myCalcInstance, new object[] { 20.0 });

Invoking public static method

double piValue = (double)type.InvokeMember("GetPi",
    BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public,
    null, null, null);
Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Related Posts:

, ,

This post was written by:

eXclusiveMinds - who has written 500 posts on eXclusiveMinds.


Contact the author

Leave a Reply

You must be logged in to post a comment.