Utilize MyClass without assuming any prior knowledge : Constructor : Reflection C# Examples


C# Examples » Reflection » Constructor »

 

Utilize MyClass without assuming any prior knowledge









    
using  System;  
using  System.Reflection;  

class  MyClass  {  
    public  MyClass(int  i)  {  
        Console.WriteLine("Constructing  MyClass(int).  ");  
    }  
  
    public  MyClass(int  i,  int  j)  {  
        Console.WriteLine("Constructing  MyClass(int,  int).  ");  
    }  
  
    public  int  sum()  {  
        return  0;  
    }  
  
    public  bool  isBetween(int  i)  {  
        return  false;  
    }  
  
    public  void  set(int  a,  int  b)  {  
        Console.Write("Inside  set(int,  int).  ");  
    }  
  
    public  void  set(double  a,  double  b)  {  
        Console.Write("Inside  set(double,  double).  ");  
    }  
  
    public  void  show()  {  
        Console.WriteLine("Values");  
    }  
}  
  
class  MainClass  {  
    public  static  void  Main()  {  
        Assembly  asm  =  Assembly.LoadFrom("main.exe");  
  
        Type[]  alltypes  =  asm.GetTypes();  
  
        Type  t  =  alltypes[0];  //  use  first  class  found  
  
        Console.WriteLine("Using:  "  +  t.Name);  
  
        ConstructorInfo[]  ci  =  t.GetConstructors();  
  
        //  Use  first  constructor  found.  
        ParameterInfo[]  cpi  =  ci[0].GetParameters();  
        object  reflectOb;  
  
        if(cpi.Length  >  0)  {  
            object[]  consargs  =  new  object[cpi.Length];  
  
            //  initialize  args  
            for(int  n=0;  n  <  cpi.Length;  n++)  
                consargs[n]  =  10  +  n  *  20;  
  
            //  construct  the  object  
            reflectOb  =  ci[0].Invoke(consargs);  
        }  else  
            reflectOb  =  ci[0].Invoke(null);  
          
    }  
}
    
   
  
   



Output

Using: MyClass
Constructing MyClass(int).


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Reflection
» Constructor