C# 4.0 dynamic Keyword
This article is about "dynamic" keyword added to C# 4.0 and It is similar to "var" keyword in C# 3.0. It is a static type and Acts as a placeholder for Object/Field which is not known till runtime. The Type will be assigned only at the runtime.
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 runtimedynamic 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.
Example:
dynamic regNo = 10; // dynamic type
int intrNo = regNo; // Converting to integer type
dynamic sname = "Sanjay"; // dynamic type
string strN = sname; // Converting to String TypeBinding 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.
Example:
//Define a class called calculator
using System;
class 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));
}
}