Introduction
Reflection concept in C# is ability of inspecting metadata of assembly at runtime meaning assembly content is described by looking at the assembly metadata at run time namespace.
When it comes to use reflection in practice scenarios it is very confusing for the developers to use refection concept properly and get benefit for this beautiful feature.
By this article I am trying to explain refection concept and the particle uses in projects.
In simple terms refection is reflection provides objects that encapsulate assemblies, modules and types meaning reflection provides a way for dynamic creation of an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties
Reflection
Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. The classes that give access to the metadata of a running program are in System.Reflection.
System.Reflection namespace defines the following types to analyze the module's metadata of an assembly: Assembly, Module, Enum, ParameterInfo, MemberInfo, Type, MethodInfo, ConstructorInfo, FieldInfo, EventInfo, and PropertyInfo.
Reflection provides objects that encapsulate assemblies, modules and types.
Assembly Metadata
I am giving a quick view about an assembly which is a logical DLL or EXE which is described by manifest which is nothing but a detailed description (metadata) of an assembly. The .NET compiler produces a portable executable PE file for CLR with the extensions of .exe or .dll. This PE file is mainly comprised of metadata and IL (Intermediate Language).
Explanation:
Whenever a .net project is build the code will be get complied into Intermediate language and then packaged in assembly. An assembly contains metadata which has the information about the type of classes defined meaning it contains all the required information about the members, fields, constructors, properties, methods, function etc used in the class for building the package.
By using refection an assembly can be inspected.
- Type _type = Type.GetType("ReflectionConcept.Employee");
- Or
- Type _type = typeof(Employee);
Sample Code
- namespace ReflectionConcept
- {
- public class Employee
- {
- public int empID { get; set; }
- public string empName { get; set; }
- public float Salary { get; set; }
-
- public Employee()
- {
- this.empID = -1;
- this.empName = string.Empty;
- this.Salary = 0;
- }
-
- public Employee(int id, string name, float salary)
- {
- this.empID = id;
- this.empName = name;
- this.Salary = salary;
- }
-
- public void displayName()
- {
- Console.WriteLine("Name :" + this.empName);
- }
-
- public void printSalary()
- {
- Console.WriteLine("Salary :" + this.Salary);
- }
-
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- Type _type = Type.GetType("ReflectionConcept.Employee");
-
-
-
-
- Console.WriteLine(_type.FullName);
- Console.WriteLine(_type.Namespace);
- Console.WriteLine(_type.Name);
-
- PropertyInfo[] info = _type.GetProperties();
-
- foreach (PropertyInfo propinfo in info)
- {
- Console.WriteLine(propinfo.Name);
- }
-
- MethodInfo [] methods=_type.GetMethods();
-
- foreach (MethodInfo methodinfo in methods)
- {
- Console.WriteLine(methodinfo.ReturnType.Name);
- Console.WriteLine(methodinfo.Name);
- }
-
- Console.ReadLine();
- }
-
-
- }
- }
Uses of Reflections
A. Refection is very heavily used by IDE developers or UI designers. Property window in .net application uses refection to show list of properties.
Still confused….alright let me take an example of web application.
In web application whenever developers drags and drop a control from control list to form. Here reflection plays the role to provide way to dynamically display all the properties of a label and these properties can be changed as per the requirement. So this concept is very important and useful for the
B. Late binding can be achieved by using refection meaning it gives developer a way to use code that is not available at compile time. By using refection instance of type can be created dynamically which don’t have information at compile time.
Important Sticky:
- It allows view attribute information at runtime.
- It allows examining various types in an assembly and instantiate these types.
- It allows late binding to methods and properties
- It allows creating new types at runtime and then performs some tasks using those types.
Late binding using reflections
Before learning late binding let us have look for the early binding.
Early Binding can be explained by the situation where the compiler knows about what kind of objects it is , what all the methods are and properties it contains.
In the example at compiler time developer has the information about the Employee class and all attributes of the class. So here in early binding we just need to create instance of the Employee class and methods, properties with that class can be used easily.
- Employee emp = new Employee();
- emp.displayName();
Late binding is nothing but binding at run time. Compiler does not know what kind of object it is, what are all the methods and properties it contains.
Late binding is achieved by using reflections.
Sample Code
- namespace ReflectionConcept
- {
- public class Employee
- {
- public int empID { get; set; }
- public string empName { get; set; }
- public float Salary { get; set; }
-
- public Employee()
- {
- this.empID = -1;
- this.empName = string.Empty;
- this.Salary = 0;
- }
-
- public Employee(int id, string name, float salary)
- {
- this.empID = id;
- this.empName = name;
- this.Salary = salary;
- }
-
- public void displayName()
- {
- Console.WriteLine("Name :" + this.empName);
- }
-
- public void displayemp(string name)
- {
- Console.WriteLine("Name :" + name);
- }
-
-
- public void printSalary()
- {
- Console.WriteLine("Salary :" + this.Salary);
- }
-
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- Assembly exceutable = Assembly.GetExecutingAssembly();
- Type Ltype =exceutable.GetType("ReflectionConcept.Employee");
-
- object objEmployee = Activator.CreateInstance(Ltype);
-
- MethodInfo method = Ltype.GetMethod("displayemp");
-
- string[] parameter = new string[1];
-
- parameter[0] = "Abhishek";
-
- string employeeName= (string)method.Invoke(objEmployee, parameter);
-
- Console.ReadLine();
- }
-
- }
- }
Early Binding Vs Late Binding
- Performance will be good in early binding.
- Application will run faster in Early binding, since no boxing or unboxing is done here but in late binding we need type conversion as it will be decoded at run time.
- Easier to write the code in Early binding, since the intelligence will be automatically populated
- Less chances errors in early binding, as syntax is checked which flags error at compile time itself but for late binding there are chances of run time exceptions.
- Late binding would support in all kind of versions, due to handing at run time.
- Minimal Impact of code in future enhancements, if Late Binding is used.
Conclusion
Above we have compared early binding and late binding features and found late binding is complex need more lines of code, venerable to run time exceptions , have issues with performance, no intelligence by .net.
So it is very important to understand where late binding should be used.
Answer would be when we are working with objects that are not available at compile time and so this can be achieved using reflections but recommended to use if you have a scenario in the project where you don’t have required information about the object available at compile time.