Inside Console Application we have an Employee class defined with FirstName property and a method called Display().
public class Employee
{
public string FirstName { get; set; }
public void Display()
{
Console.WriteLine("Hi, my name is {0}",FirstName);
}
}
Inside the Program imagine I am calling a method called GetName() which return an object
class Program
{
static void Main(string[] args)
{
}
public static object GetName()
{
return new Employee {FirstName = "Jameel"};
}
}
Then I am going to assign this method to an object in the main method
static void Main(string[] args)
{
object o = GetName();
}
How can I invoke the Display () method?
One way is call like below
Employee employee = GetName() as Employee;
employee.Display();
What we do when we don’t know the type of Display() method?
Ofcourse we can use reflection
object o = GetName();
o.GetType().GetMethod("Display").Invoke(o, null);
Dynamic typed variable could give the same result with less code.Note that C# and Visual Studio doesn’t give the intellisense.In compile time Compiler doesn’t know about the Display() method only runtime can understand it.
dynamic o = GetName();
o.Display();
Create one more class library by right clicking the solution and create a new class library project named Animals and add a new class named Animal with an method called Display()
public class Animal
{
public void Display()
{
Console.WriteLine("Elephant");
}
}
Our previous Console mode application don’t know about this because we not add the reference to this project. So that compiler doesn’t know about this assembly.
We can also the Display() method by dynamically loading this assembly.
Type animalType = Assembly.Load("Animals").GetType("Animal");
dynamic animal = Activator.CreateInstance(animalType);
animal.Display();
dynamic keyword help us to remove type casting from our code, reflection codes GetMember(),GetType() and GetProperty() and the Invoke method that try to set and get things. All of these things clean up with the dynamic keyword.
Enjoy Reading…