C# 4.0 dynamic keyword


C# 4.0 dynamic keyword is used to declare the variable and object whose type will be resolved at runtime. Here with giving the code snippet to show how dyanmic keyword can be used to implement method overloading concept in C# 4.0

dynamic keyword is introduced in C# 4.0. It is used to declare variable and objects whose type will be determined at runtime. When the dynamic keyword is used in method overload concept. It can take any type of value as its parameter.
// C# 4.0 dynamic keyword - in Method Overloading


using System;
class dynamicDemo {
// Method takes dynamic type value as parameter
public void display(dynamic a){
Console.WriteLine("a's value = " + a);
Console.WriteLine("a's Datatype = " + a.GetType());
}

public void display(dynamic a, dynamic b) {
Console.WriteLine("a's value = " + a);
Console.WriteLine("a's Datatype = " + a.GetType());
Console.WriteLine("b's value = " + b);
Console.WriteLine("b's Datatype = " + b.GetType());
}

public void display(dynamic a, dynamic b, dynamic c){
Console.WriteLine("a's value = " + a);
Console.WriteLine("a's Datatype = " +
a.GetType());
Console.WriteLine("b's value = " + b);
Console.WriteLine("b's Datatype = " +
b.GetType());
Console.WriteLine("c's value = " + c);
Console.WriteLine("c's Datatype = " +
c.GetType());
}

static void Main(string[] args) {
dynamic objD = new dynamicDemo();

// passing String value as parameter
Console.WriteLine("String Value Parameter");
objD.display("Sanjay");

Console.WriteLine("\n\nFloat Value Parameter");
objD.display(456.45);

// Two value parameters
Console.WriteLine("String Value Two Parameter");
objD.display("Vijaya", "Lakshmi" );
Console.WriteLine("\n\nInteger Value Two Parameter");
objD.display(100, 300.45);


//Three value parameters
Console.WriteLine("\n\nThree Parameter Integer, String and Float");

objD.display(204, "Kala" , 200.50);

Console.WriteLine("\n\n Three parameters String, Integer and Float");
objD.display("abc", 80, 23.89);
Console.ReadKey();
}
}


Comments

Author: Tom26 Nov 2011 Member Level: Bronze   Points : 0

Nice post on .net new features.
Click here to read more about .Net 4.0 http://www.codinghub.net/2011/11/tutorial-aspnet-40-new-features-1.html

Author: Vijayalakshmi G M27 Nov 2011 Member Level: Gold   Points : 0

Hi Tom,

Thank You for your feedback and link which your shared in the response.

Author: Siva Prasad26 Mar 2012 Member Level: Gold   Points : 0

Nice example on c# 4.0 fetures.

Author: Vijayalakshmi G M26 Mar 2012 Member Level: Gold   Points : 0

Hi Siva Prasad,

Thank You for your feedback.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: