In this Article, I will discuss Dynamic Type in C#:
Dynamic Type
'Dynamic' keyword is used to declare the variable of the dynamic type. Dynamic data type variable can contain any type of value. Type of value contained is checked at runtime. The syntax of Dynamic type is shown below:
Dynamic <VariableName> = value;
'Dynamic' keyword is similar to 'var' keyword or you can think it as a replacement for var keyword. Unlike 'var', it is not necessary to initialize dynamic variable while declaring. Dynamic types are used in many cases as shown below:
1) Multiple declarations of a variable with different data types:
With dynamic, we can have multiple initializations of a variable of different data types. Like a variable named 'sample' can contain int, float, bool, string etc. values in a class as shown below in the example:
- using System;
- namespace Tutpoint
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("hello Tutpoint");
- dynamic sample;
- sample = 12;
- Console.WriteLine(sample);
- sample = 0.222;
- Console.WriteLine(sample);
- sample = true;
- Console.WriteLine(sample);
- sample = "Dynamic";
- Console.WriteLine(sample);
- sample = null;
- Console.ReadLine();
- }
- }
- }

Mahesh ChandPosted Sep 22, 2010, 7:20 AM
Thank you for sharing Anand.