About dynamic Keyword
1. "dynamic" is a new keyword added to C# 4.0
2. It is similar to "var" keyword in C# 3.0.
3. It is a static type.
4. It acts as a placeholder for Object/Field which is not known till runtime.
5. Type will assigned only at runtime
dynamic variable declaration
dynamic regNo = 10;
dynamic sname = "Sanjay";
Note: Datatype will be assigned to the variable at runtime, based on value stored in the variable.
GetType() Method is used to know the dynamic value's datatype.
dynamic value Conversion
dynamic values to other types are easy.
dynamic regNo = 10; // dynamic type
int intrNo = regNo; // Converting to integer type
dynamic sname = "Sanjay"; // dynamic type
string strN = sname; // Converting to String Type
Binding the object at runtime
1. Any object reference can be applied to the dynamic type object, later
dynamic object is used to invoke the method from the class.
//Define a class called calculator
public int Add(int a, int b)
return a + b;
static void Main(string args)
// statically binded
Calculator objC = new Calculator();
Console.WriteLine("Sum = " + objC.Add(10, 50));
// dynamically binded object
//Assign Calculator Class object reference to dynamic object dobjC
dynamic dobjC = new Calculator();
//Invoke the method using dynamic object.
Console.WriteLine("Sum " + dobjC.Add(10, 30));
No responses found. Be the first to comment...