Reflection in C#

An Example

One very useful feature related to reflection is the ability to create object dynamically and call methods on them. You can specify which class you want a Type object, or by giving the name of an assembly and a class as string, so this makes it possible to get the name of a class from the user and create an object of the appropriate type. You can then interact with the new object just as if you’d created it with new, and use reflection to find out just you’re dealing with and what it can do.

Following C# code will demonstrate the reflection capabilities.

namespace reflect
{
using System ;
using System.Reflection ;

publicclass ClassA
{

  publicstaticint Main ( string[] kami )
  {
    Type t = typeof( test ) ;
    Console.WriteLine ( "Type of class: " + t ) ;
    Console.WriteLine ( "Namespace: " + t.Namespace ) ;
    ConstructorInfo[] ci = t.GetConstructors( );
    Console.WriteLine( "Constructors are:" ) ;
 
    foreach( ConstructorInfo i in ci )
    {
     Console.WriteLine( i ) ;
    }
 
    PropertyInfo[] pi = t.GetProperties( );
    Console.WriteLine( "Properties are:" ) ;
 
    foreach( PropertyInfo i in pi )
    {
     Console.WriteLine( i ) ;
    }
    MethodInfo[] mi = t.GetMethods( ) ;
    Console.WriteLine( "Methods are:" ) ;
 
    foreach( MethodInfo i in mi )
    {
     Console.WriteLine( "Name: " + i.Name ) ;
     ParameterInfo[] pif = i.GetParameters () ;
     foreach ( ParameterInfo p in pif )
      {
        Console.WriteLine("Type: " + p.ParameterType + " parameter name: " + p.Name ) ;
      }
    }
    return 0 ;
  }
}


publicclass test
{
  int i ;
  int prop;

  publicint Prop
  {
    get
    {
      return prop ;
    }
    set
    {
      prop = value ;
    }
  }
 
  public test()
  {
  }
 
  public test ( int x )
  {
    i = x ;
  }

  publicint funcA ( int x )
  {
    Console.WriteLine ( x ) ;
    return 2 * x ;
  }
}
}

You might also like...

Comments

About the author

Kamran Shakil Pakistan

I am 22 male. BS(Computer Science), MCSE, Brainbench certifed. Member of .NET Open source, Mono Project. E-author on various websites, including www.dotnetextreme.com, www.csharphelp.com and so...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity.” - Dennis Ritchie