Demonstrate dynamically invoking an object

image_pdfimage_print
   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// Invoke.cs -- Demonstrate dynamically invoking an object
//
//              Compile this program with the following command line:
//                  C:>csc Invoke.cs
using System;
using System.Reflection;

namespace nsReflection
{
    public class Invoke
    {
        static public void Main ()
        {
            // Load the Circle assembly.
            Assembly asy = null;
            try
            {
                asy = Assembly.Load ("Circle");
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
                return;
            }
            
            // Parameter array for a POINT object.
            object [] parmsPoint = new object [2] {15, 30};
            
            // Parameter array for a clsCircle object.
            object [] parmsCircle = new object [3] {100, 15, 30};
            
            // Get the type of clsCircle and create an instance of it.
            Type circle = asy.GetType("nsCircle.clsCircle");
            object obj = Activator.CreateInstance (circle, parmsCircle);
            
            // Get the property info for the area and show the area
            PropertyInfo p = circle.GetProperty ("Area");
            Console.WriteLine ("The area of the circle is " + p.GetValue(obj, null));
            
            // Get the POINT type and create an instance of it
            Type point = asy.GetType("nsCircle.POINT");
            object pt = Activator.CreateInstance (point, parmsPoint);
            
            // Show the point using object's ToString() method
            Console.WriteLine ("The point is " + pt.ToString ());
        }
    }
}