Reflection in C# with Example

Reflection in C# with Example
Rating: 5 - 2 Votes

Reflection in C# with Example

C# Reflection ExampleIn this C# reflection tutorial, you will learn what is reflection in C# and how to use it.  In dotnet, whenever you compile an application, an assembly is generated.  That assembly could be an executable file or a dll file.  As we know, all dotnet applications contains MSIL or CIL code which is converted to machine specific code by JIT compiler at runtime.  Apart from MSIL code, a compiled assembly contains metadata and manifest which provides version info, copyright info etc.  MSIL code, metadata, and manifest can be easily viewed with the help of ildasm.exe tool.  You can also obtain same information programmatically with the help of reflection in dotnet.

Metadata in an assembly contains all the information about types including classes, structures, interfaces, enumerations, and delegates.  Even throughout your coding process, intellisense highly rely on these types.   Metadata is basically a set of tables which are marked as TypeDef and TypeRef.   TypeDef points to the type in the current assembly and TypeRef points to the type in an external assembly.

Since MSIL code is not easy to understand for a dotnet beginner, reflection services come into play.  Reflection services help us in retrieving all the information about types as well as methods, fields, and properties defined within it.  If you really want to dig more deeper into an assembly, then you can easily obtain set of interfaces support by a type, base class, information about namespace , method parameters,  etc.  All reflection services belong to System.Reflection namespace.

As we know, a type can have more than one field, method, or property.  All these members are retrieved in the form of an array using System.Type class.  We have a couple of abstract classes in System.Reflection like MethodInfo, PropertyInfo, FieldInfo etc.  Using Type.GetMethods(), we can get an array of MethodInfo which will contain info about all the available methods in a given type.  Same logic goes for fields, properties, and others.

A very commonly used method in Type class is GetType() which will return the type of an object.  GetType() is static method and it can be called directly by any instance of an object.   The another approach for same output will be TypeOf operator.  But it is more error prone because it does not check for compile time errors which means any random string name can be passed as parameter to obtain its type.

A small C# reflection example of obtaining methods available in a class using reflection services is given below, which will give you a basic idea of how to use reflection in C#.