Reflection

Hi, just thought to share little knowledge on reflection with you all, as per being a developer, I was very curious to find how visual studio is giving intellisence, that took me to learn reflection and I found its really good to know about it.so I will start with using a pattern, in this way you will get to know about two things. 🙂

Reflection and Abstract Factory pattern.

Below is sample snippet of same.

interface Product{}
class ConcreteProductA : Product{}
class ConcreteProductB : Product{}
abstract class Creator
{
 public abstract Product FactoryMethod(string type);
}
class ConcreteCreator : Creator
{
 public override Product FactoryMethod(string type)
 {
 switch (type)
 {
 case "A": return new ConcreteProductA();
 case "B": return new ConcreteProductB();
 default: throw new ArgumentException("Invalid type", "type");
 }
 }
}

Here you can see that we are using a switch case with some passing value based on which code will differentiate which concrete class to instance. And so if needs to add any other class type will need to add another case into this Factory class as well.
Which will not be needed if we use reflection for same.

class ConcreteCreator : Creator
 {
 public override Product FactoryMethod(string assemblyQualifiedName)
 {
 Type t = Type.GetType(assemblyQualifiedName);
 IStudents students = Activator.CreateInstance(t) as IStudents;
 return students;
 }
 }

So, additional coding decreases.
Now you know two things
  1. Where to use Reflection
  2. Abstract Factory pattern
Another use of reflection
Accessing private properties, methods of classes.

 public class Employee
 {
 public Employee() { ... }
 private double _number;
 public double Number { get { ... } set { ... } }
 public void Clear() { ... }
 private void DoClear() { ... }
 public double AddEmployee(Employee employee) { ... }
 }

Let’s say we have a class as shown above.
And it’s having few private methods and we need to access any of them.

 Employee emp = new Employee();
 Type empType= typeof(Employee);
 // invoke private instance method: private void DoClear()
 empType.InvokeMember("DoClear",
 BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
 null, calc, null);

This way we can call any private method of any class, or from any dll as well.
You just needs to know if it is there or not, which can easily done by using ObjectExplorer in visual studio, or by ildasm.exe.

🙂 Happy Coding 🙂

Written By: Ajay Kumar, Software Engineer, Mindfire Solutions

 

Posted on August 28, 2014, in C# and tagged , , , , , , . Bookmark the permalink. 1 Comment.

Leave a reply to vipinj Cancel reply