5,286,006 members and growing! (20,026 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

Reflection in C# Tutorial

By Idemudia Esangbedo

Reflection in C# Tutorial
C# 2.0, C#, Windows, .NET, .NET 2.0, Visual Studio, Dev

Posted: 21 Jan 2007
Updated: 28 Aug 2007
Views: 22,541
Announcements



Search    
Advanced Search
Sitemap
19 votes for this Article.
Popularity: 4.06 Rating: 3.17 out of 5
3 votes, 15.8%
1
4 votes, 21.1%
2
1 vote, 5.3%
3
2 votes, 10.5%
4
9 votes, 47.4%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

Reflection in C#

Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and types 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 able to 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 below code snippet will get the method's information. And the method we are interested in this case is the "AddNumb":

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

And the below 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 theMyClass2 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 object 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 the 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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Idemudia Esangbedo



Occupation: Web Developer
Location: United States United States

Other popular C# Programming articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 5 of 5 (Total in Forum: 5) (Refresh)FirstPrevNext
Subject  Author Date 
Generalplz help..membernareshpersi4:58 25 Apr '08  
QuestionHow do you handle over loaded methods?memberBrad Thompson8:33 26 Nov '07  
AnswerRe: How do you handle over loaded methods?memberIdemudia Esangbedo10:27 1 Dec '07  
GeneralGood Articlemembermerlin9815:54 29 Aug '07  
GeneralFormattingmemberStockportJambo20:50 21 Jan '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 28 Aug 2007
Editor:
Copyright 2007 by Idemudia Esangbedo
Everything else Copyright © CodeProject, 1999-2008
Web10 | Advertise on the Code Project