Click here to Skip to main content
15,902,635 members
Articles / Programming Languages / C#

Reflection for freshers

Rate me:
Please Sign up or sign in to vote.
1.54/5 (6 votes)
13 Jun 2007CPOL1 min read 15.9K   83   12   1
Some examples of Reflection which may be useful for fresh .NET developers.

Introduction

It is always good to know a little bit about a topic before starting to read the MSDN or a book. Here the aim is to show simple examples which can be used as a start for studying "Reflection in .NET".

Background

I have always liked to see some sample programs before getting deep into the theory.

Using the code

Reflection can be used to:

  1. Analyze and inspect an object.
  2. Manipulate or invoke an object at run time.

You can find a lot of other definitions and uses for "Reflection". But I am concentrating on the above two.

I have a class here called Reflect1:

C#
class Reflect1
{
    private int MyData = 100;
    public void Fn1() { }
    public int Fn2()
    {
        return MyData;
    }
    public int Property1
    {
        get {
        return MyData;}
        set{
        MyData = value;}
    }
}

In order to retrieve the different methods and properties implemented by the Reflect1 class, I can make use of the different methods provided by "System.Reflection". For example, in order to retrieve the method names and their return types, the following code will help:

C#
Reflect1 obj1 = new Reflect1();
Type t1 = obj1.GetType();
Console.WriteLine("Type Name is {0}", t1.Name);
foreach (MethodInfo mi in t1.GetMethods(BindingFlags.Public | 
         BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
    Console.WriteLine("Method Name is {0}", mi.Name);
    Console.WriteLine("Return Type for the method is {0}", mi.ReturnType.Name); 
}

We can even access the data of a private member variable if we know the name of the variable. So here I know that the name of the member variable is MyData.

C#
Type t3 = typeof(Reflect1);
FieldInfo fi = t3.GetField("MyData", 
          BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine("Field Name is {0}", fi.Name);
Console.WriteLine("Field Type is {0}", fi.FieldType.Name);
Console.WriteLine("Field Type is {0}", (int)fi.GetValue(obj1));

The next is invoking a method at runtime. See the following code:

C#
class Base
{
    private int myBaseVal;
    public Base(int b)
    {
        myBaseVal = b;
    }
    public virtual void ReturnVal()
    {
        Console.WriteLine("Base.ReturnVal is called");
    }
}

class Derived : Base
{
    public Derived(int b) : base(b)
    { 
    }
    public override void ReturnVal()
    {
    Console.WriteLine("Derived.ReturnVal is called");
    }
}

Base obj2 = new Base(10);
Type t4 = obj2.GetType();
Console.WriteLine("Type Name is {0}", t4.Name);
foreach (MethodInfo mi in t4.GetMethods(BindingFlags.Instance | 
         BindingFlags.Public | BindingFlags.DeclaredOnly))
{
    mi.Invoke(obj2, null);
}

Base obj3 = new Derived(100);
Type t6 = typeof(Base);
Console.WriteLine("Type Name is {0}", t6.Name);
MethodInfo mi6 = t6.GetMethod("ReturnVal");
mi6.Invoke(obj3, null);

I am not checking for any exception or null values as this is a sample code.

Now you can start reading a good book on .NET Reflection.

License

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


Written By
Web Developer
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Dave Kreskowiak30-Aug-09 10:34
mveDave Kreskowiak30-Aug-09 10:34 

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

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