Click here to Skip to main content
11,488,877 members (76,607 online)
Click here to Skip to main content

Reflection in C# Tutorial

, 28 Aug 2007 CPOL 364.7K 93
Rate this:
Please Sign up or sign in to vote.
Reflection in C# Tutorial

Introduction

Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. In other words, reflection provides objects that encapsulate assemblies, modules and types. A program reflects on itself by extracting metadata from its assembly and using that metadata either to inform the user or to modify its own behavior. Reflection is similar to C++ RTTI (Runtime Type Information), but much broader in scope and capability. By using Reflection in C#, one is able to find out details of an object, method, and create objects and invoke methods at runtime. The System.Reflection namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types. When writing a C# code that uses reflection, the coder can use the typeof operator to get the object's type or use the GetType() method to get the type of the current instance. Here are sample codes that demonstrate the use of reflection:

Example 1

using System;
using System.Reflection;

public class MyClass
{
   public virtual int AddNumb(int numb1,int numb2)
   {
     int result = numb1 + numb2;
     return result;
   }

}

class MyMainClass
{
  public static int Main()
  {
    Console.WriteLine ("\nReflection.MethodInfo");
    // Create MyClass object
    MyClass myClassObj = new MyClass();
    // Get the Type information.
    Type myTypeObj = myClassObj.GetType();
    // Get Method Information.
    MethodInfo myMethodInfo = myTypeObj.GetMethod("AddNumb");
    object[] mParam = new object[] {5, 10};
    // Get and display the Invoke method.
    Console.Write("\nFirst method - " + myTypeObj.FullName + " returns " +  
                         myMethodInfo.Invoke(myClassObj, mParam) + "\n");
    return 0;
  }
}

Firstly, the code snippet below will get the type information:

Type myTypeObj = Type.GetType("MyClass");

And myTypeObj will now have the required information about MyClass. Therefore we can now check if the class is an abstract class or a regular class by using either of these statements:

myTypeObj.IsAbstract 

or:

myTypeObj.IsClass 

The code snippet below will get the method's information. And the method that we are interested in this case is AddNumb:

Methodinfo myMethodInfo = myTypeObj.GetMethod("AddNumb"); 

The following code snippet will invoke the AddNumb method:

myMethodInfo.Invoke(myClassObj, mParam);
//Example2: In this example, we will use the typeof keyword to obtain the
//          System.Type object for a type.

Public class MyClass2
{
  int answer;
  public MyClass2()
  {
    answer = 0;
  }

  public int AddNumb(intnumb1, intnumb2)
  {
    answer = numb1 + numb2;
    return answer;
  }
}

The code snippet below gets the System.Type object for the MyClass2 type.

Type type1 = typeof(MyClass2);

So we will now be able to create an instance of the type1 object by passing the type1 object to the Activator.CreateInstance(type1) method.

object obj = Activator.CreateInstance(type1);

Then we can now invoke the AddNumb method of the MyClass2 class by first creating an array of objects for the arguments that we would be passing to the AddNumb(int, int) method.

object[] mParam =newobject[] {5, 10}; 

Finally, we would invoke the AddNumb(int, int) method by passing the method name AddNumb to System.Type.InvokeMember() with the appropriate arguments.

int res = (int)type1.InvokeMember("AddNumb", BindingFlags.InvokeMethod,null,
                                  obj, mParam);
//Here is the complete code:
using System;
using System.Reflection;

namespace Reflection
{
   class Class1
   {
    public int AddNumb(int numb1, int numb2)
    {
      int ans = numb1 + numb2;
      return ans;
    }

  [STAThread]
  static void Main(string[] args)
  {
     Type type1 = typeof(Class1); 
     //Create an instance of the type
     object obj = Activator.CreateInstance(type1);
     object[] mParam = new object[] {5, 10};
     //invoke AddMethod, passing in two parameters
     int res = (int)type1.InvokeMember("AddNumb", BindingFlags.InvokeMethod,
                                        null, obj, mParam);
     Console.Write("Result: {0} \n", res);
   }
  }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Idemudia Sanni Esangbedo
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
Generalthanks Pin
hope_amal10-Apr-15 5:25
memberhope_amal10-Apr-15 5:25 
QuestionCan you give some real world scenario for Reflection? Pin
GANESH289014-Mar-15 9:19
memberGANESH289014-Mar-15 9:19 
QuestionTo view all class and methods in a project. Pin
Member 114934062-Mar-15 20:26
memberMember 114934062-Mar-15 20:26 
GeneralMy vote of 4 Pin
Sibeesh Venu1-Aug-14 21:29
professionalSibeesh Venu1-Aug-14 21:29 
GeneralThanks Pin
lokesh lokesh22-Jul-14 22:28
memberlokesh lokesh22-Jul-14 22:28 
QuestionRegarding GetMethod("AddNumb"); Pin
Member 103341569-May-14 1:58
memberMember 103341569-May-14 1:58 
GeneralMy vote of 5 Pin
Amol_B18-Mar-14 0:06
professionalAmol_B18-Mar-14 0:06 
GeneralMy Vote 5 Pin
Shivarajbk20-Feb-14 2:26
memberShivarajbk20-Feb-14 2:26 
QuestionGood tutor Pin
Member 41187049-Jul-13 17:59
memberMember 41187049-Jul-13 17:59 
GeneralMy vote of 4 Pin
Ubiratan Rodrigues15-Apr-13 9:49
memberUbiratan Rodrigues15-Apr-13 9:49 
GeneralMy vote of 4 Pin
JamesChenHi22-Jan-13 22:09
memberJamesChenHi22-Jan-13 22:09 
GeneralMy vote of 1 Pin
Rahul (Software Engineer)9-Jul-12 1:58
memberRahul (Software Engineer)9-Jul-12 1:58 
GeneralMy vote of 5 Pin
vinothmkgfslppy1-May-12 23:09
membervinothmkgfslppy1-May-12 23:09 
GeneralGood tuto Pin
innuendoreplay1-Oct-11 12:28
memberinnuendoreplay1-Oct-11 12:28 
GeneralMy vote of 1 Pin
OpenSessame16-Feb-10 2:19
memberOpenSessame16-Feb-10 2:19 
you are not saying anything that is not in the help file
GeneralGood intro Pin
Rami Shareef29-Jan-10 6:55
memberRami Shareef29-Jan-10 6:55 
QuestionReflection , Invoke Methods using System.Reflection Pin
Nouman_gcu29-Oct-09 4:42
memberNouman_gcu29-Oct-09 4:42 
AnswerRe: Reflection , Invoke Methods using System.Reflection Pin
Idemudia Esangbedo15-Nov-09 10:32
memberIdemudia Esangbedo15-Nov-09 10:32 
GeneralI tried with Reflection Code in this article however it is not working for me Pin
puneet.bhatnagar123@gmail.com7-Oct-08 0:24
memberpuneet.bhatnagar123@gmail.com7-Oct-08 0:24 
GeneralRe: I tried with Reflection Code in this article however it is not working for me [modified] Pin
Idemudia Esangbedo9-Oct-08 9:08
memberIdemudia Esangbedo9-Oct-08 9:08 
GeneralRe: I tried with Reflection Code in this article however it is not working for me Pin
Puneet Bhatnagar15-Oct-08 1:14
memberPuneet Bhatnagar15-Oct-08 1:14 
Generalplz help.. Pin
nareshpersi25-Apr-08 4:58
membernareshpersi25-Apr-08 4:58 
GeneralRe: plz help.. Pin
Mircea Sirghi4-Oct-08 2:33
memberMircea Sirghi4-Oct-08 2:33 
QuestionHow do you handle over loaded methods? Pin
Brad Thompson26-Nov-07 8:33
memberBrad Thompson26-Nov-07 8:33 
AnswerRe: How do you handle over loaded methods? Pin
Idemudia Esangbedo1-Dec-07 10:27
memberIdemudia Esangbedo1-Dec-07 10:27 
GeneralGood Article Pin
merlin98129-Aug-07 5:54
membermerlin98129-Aug-07 5:54 
GeneralFormatting Pin
StockportJambo21-Jan-07 20:50
memberStockportJambo21-Jan-07 20:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 28 Aug 2007
Article Copyright 2007 by Idemudia Sanni Esangbedo
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid