.Net Reflection Example in C#

Reflection is a special type of class in c# programming that help us reading metadata information of any assembly, reading their internal structure, in this post, you learn about Reflection class under System.Reflection namespace.

Use C# Reflection Class for reading metadata information, PropertyInfo, MethodInfo in c# .net program!

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

Use .Net Reflection Class

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

Now think of a task that gives you an opportunity to use reflection class, try reading all sql table information in your csharp code, and create class for every single table and views, create entity for your orm program.

 
.Net Reflection Example
.Net C# Programming Tutorials
Online Tutorials
C# .net Interview Questions Answers
.Net C# Examples | Join .Net C# Course