Free Web Development Online Tutorials, Learn to Code
Reflection in asp.net with example, Learn C# programming Language, Free C# Tutorial for Beginners

.Net Reflection Example in C#

How to use C# Reflection Class in Program!

In this article you learn about Reflection under System.Reflection namespace

What is Reflection in .Net?

Under System.Reflection there are few classes that helps getting metadata information at runtine. we also can retrieve information on the loaded assemblies and their defined types.

To understand reflection you should understand about modules, types, and members

  • Assemblies contain modules
  • Modules contain types
  • Types contain members

using System.Reflection;
        
MemberInfo info = typeof(StackSample);

How to use .Net Reflection and why?

You can use reflection using System.Reflection namespace, to create an instance of any type dynamically and then even invoke the methods of the instance type .

In this example we will create one assembly with just one class as given below, and will see how to retrieve metadata information using reflection in C#.

namespace WTRConsoleApplication
{
    class ReflectionExample
    {
        public string SystemTypeName { get; set; }          
        public int GetCharCount(string content)
        {
        int _result = 0;
        if (!string.IsNullOrEmpty(content))
        _result = content.Length;
        return _result;
        }
    }
}

After compilation of above code in Console appliaction we got an assembly called "WTRConsoleApplication.exe"

Cerate instance of a class using reflection in C#

Now we load the assembly and pick the above class from metadata at runtime using Reflection and then create an instance (Activator.CreateInstance) of above class.

Here are few things to notice:

  • Load Assembly using LoadFile method
  • Get the class type with GetType method
  • Create a new instance of newly loaded class dynamically using Activator CreateInstance method

using System.Reflection;
Assembly testAssembly = Assembly.LoadFile(@"D:\MyProjects\WTRConsoleApplication.exe");
Console.WriteLine("Assembly loaded successfully");
Console.WriteLine("\n");
// get the class type ReflectionExample from just loaded WTRConsoleApplication assembly
Type _ReflectionExampleType = testAssembly.GetType("WTRConsoleApplication.ReflectionExample");
Console.WriteLine("ReflectionExample type got Correctly " + _ReflectionExampleType.ToString());
Console.WriteLine("\n");
// create instance of ReflectionExample Class
object _instanceReflectionExample = Activator.CreateInstance(_ReflectionExampleType);

            
Console.WriteLine("Instance created successfully");
Console.WriteLine("\n");

Reflection PropertyInfo in C#

In below code we retrieve the property called "SystemTypeName" from above instance Of "ReflectionExample" class, then set a new value to that property and finally read the same vale to check if the value set was done correctly

Things to learn:

  • Get the PropertyInfo of any specified property
  • Set value of property: public string type (for testing)
  • Now read the new value from that property

// get the PropertyInfo of any specified property
PropertyInfo _propinfoSystemTypeName = _ReflectionExampleType.GetProperty("SystemTypeName");
Console.WriteLine("get the property we want to experiment with");

// set value of property: public string type
_propinfoSystemTypeName.SetValue(_instanceReflectionExample, "WebTrainingRoom Tutorial");
Console.WriteLine("set new value to property at runtime");


// now read the new value from that property
Console.WriteLine(_propinfoSystemTypeName.GetValue(_instanceReflectionExample));
Console.WriteLine("read the new value of property at runtime");

Reflection MethodInfo Example in C#

Here you learn how to invoke a method with parameter at runtime using Reflection in C#.

Note: we are using the same instance we created in earlier code block

// get the MethodInfo of any specified method
MethodInfo _methodGetCharCount = _ReflectionExampleType.GetMethod("GetCharCount");

string[] paramas = new string[] { "This is a test parameter value to my method GetCharCount" };

Console.WriteLine(_methodGetCharCount.Invoke(_instanceReflectionExample, paramas));
Console.WriteLine("Invoke the method with  parameter at runtime using reflection");

Notice _methodGetCharCount.Invoke(_instanceReflectionExample, paramas)
Invoke method will return object type as result, then you need to cast to appropriate type

Hope you enjoyed our C# Reflection Tutorial! Have Fun with Illustration !

C# reflection example

Comment
Name
Email
Website
Subscribe
 

.Net Reflection Example
Other Online Tutorial

C# .net Interview Questions Answers

Get metadata information, PropertyInfo, MethodInfo using Reflection in C# .Net