What is Reflection in C#?
- Reflection is the ability of a code to access the metadata of the assembly during runtime. A program reflects upon itself and uses the metadata to inform the user or modify its behavior. Metadata refers to information about objects, methods.
- The namespace System.Reflection contains methods and classes that manage the information of all the loaded types and methods. It is mainly used for windows applications, for Example, to view the properties of a button in a windows form.
- The MemberInfo object of the class reflection is used to discover the attributes associated with a class.
- Reflection is implemented in two steps, first, we get the type of the object, and then we use the type to identify members such as methods and properties.
- To get type of a class, we can simply use
- Type mytype = myClass.GetType();
- Once we have a type of class, the other information of the class can be easily accessed.
- System.Reflection.MemberInfo Info = mytype.GetMethod(“AddNumbers”);
- Above statement tries to find a method with name AddNumbers in the class myClass.
No comments