You can get type information, read manifest or read metadata
from an assembly using reflection programmatically. Late binding also can
achieve using reflection. Using reflection application can get the information
about itself. Method can invoke using reflection. You can get the information
about type, properties, methods and event object. We can create object of a
class or use existing object using reflection.
System.Reflection namespace along with System.Type used in
getting information from an assembly. System.Type is an abstract class, its
represent a type in Common Type System.
System.Type represent type declaration such as class type,
array type, interface type, value type, enumeration type , open or close
constructed generic type.
You can get the type object using two ways.
1.
Using GetType() method of Type
class
Type t = Type.GetType("Reflection.Car", false, true);
Console.WriteLine(t.FullName);
Where Reflection is namespace and Car is a class name.
Ouput
Reflection.Car
2.
Using typeof() operator.
/////////////////////////////////////////
// Get the Type using typeof.
Type t = typeof(Car);
Console.WriteLine(t.FullName);
////////////////////////////////////
Ouput
Reflection.Car
Benefits
1.
Get the type of an object at runtime.
2.
Load an assembly at runtime and call meth\od dynamically at runtime. Basically
useful for people who are working in an environment where configuration is changing
at runtime.
3.
Get object information at runtime even call them
4.
Late binding
5.
Can create a class at runtime using Reflection.Emit
6.
Can create property and methods at runtime using PropertyBuilder and
MethodBuilder.
7.
Activator.CreateInstance() method can be used to create object at runtime.
8.
Dynamic keyword introduced in .Net 4.0 uses reflection internally.
Practical Use of Reflection
1. Property window of visual studio is a live example of reflection where
it reads the all properties of object and show them
2. In unit testing framework, you need to call method and properties
dynamically.
3. Sometimes need to show all class information in a text file.
Difference Between Reflection and dynamic
1.
Using dynamic only public members can invoke while using reflection both
can be invoke.
2.
Using dynamic only instance member can invoke while using reflection
static members also cab invoke.
3.
Dynamic is a keyword introduce in .Net 4.0 while reflection is a
mechanism to inspect the meta data of an object at runtime. Dynamic cannot
inspect the metadata about an object.