Reflection is used to get the type information at runtime. In reflection, we retrieve the type instance which describes the assemblies, types, and modules. Using reflection we can get the information about an existing type and can also invoke its methods and access its properties. The following code gets the type instance for an integer variable.
- int i=1;
- Type type = i.GetType();
We can get the type information for the integer type using this type instance. For example, if we want the assembly information for the integer type then we can use the following code:
- Console.WriteLine(type.Assembly);
We get the following output for the statement above. As we can see, we get all the details for the containing assembly of the type.
We use attributes to associate metadata with a class. We are not restricted to using only the built-in attributes. We can create our own custom attributes if required. We define a custom attribute as a class deriving from the Attribute class.
When we define custom attributes in the source code we should be able to access that information at runtime. We can use reflection to access the information defined using custom attributes. In the following code, we are first defining a custom attribute called Employee and then attaching it to a class.
- [System.AttributeUsage(System.AttributeTargets.Class,AllowMultiple = true)]
- public class Employee : System.Attribute
- {
- string name;
- public Employee(string name)
- {
- this.name = name;
- }
- public string GetName()
- {
- return name;
- }
- }
- [Employee("Ashish Shukla")]
- public class TestClass
- {
- }

Hamid KhanPosted Feb 12, 2021, 8:03 PM
Very nice...............