Friday, September 10, 2010

How to get a property and call a method of class using reflection

Sometime you get an error when declare an object belongs to class, but before declare an object you must add that dll as a reference. but the problem is whether that dll is existed or not and what happend if that dll does not exist? On hundred percent is to throw exception because you are calling a method or property of object but it does not initialize. The best way is to reflect that class to object and not necessary to add that dll as reference.

I have a dll was built from the project named "example", here is the code


namespace Example
{
    public class Calculate
    {
        public Calculate()
        {
        }


        private int a = 0;
        public int A
        {
            get
            {
                return this.a;
            }
            set
            {
                this.a = value;
            }
        }


        private int b = 0;
        public int B
        {
            get
            {
                return this.b;
            }
            set
            {
                this.b = value;
            }
        }


        public int Plus()
        {
            return this.A + this.B;
        }


        public int Multiple()
        {
            return this.A * this.B;
        }


        public int Substract()
        {
            return (this.A - this.B);
        }


        public int Divide()
        {
            if (this.B == 0) throw new ApplicationException("Do not allow null !");
            return this.A / this.B;
        }
    }
}

The class is very simple to execute the calculating 2 numbers A and B. Now I have another project need to use this class, but I dont want to add this dll into my reference. If this dll was not installed, you will get an error when you build this project. So, I have another way, look at my code



        Type asmCal = asm.GetType("MyReflection.Calculate");


        object obj = Activator.CreateInstance(asmCal);


        //here you can detect obj and asmCal are not null before doing any thing bellow
        //set A property
        asmCal.InvokeMember("A", BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance, null, obj, new object[] { 5 });


        //set B property
        asmCal.InvokeMember("B", BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance, null, obj, new object[] { 5 });


        int plus = (int)asmCal.InvokeMember("Plus", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, null);

No comments: