dynamic keyword example in CSharp – Demo1

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…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s