What if we are not sure of the type of value that we want to store in a variable. How to handle this in C#?

CsharpServer Side ProgrammingProgramming

As C# is a strongly-typed language, every variable and constant has a pre-defined type. Before using any variable, we must tell the compiler what type of value a variable will store.

If we are not sure about the type, then it is handled using dynamic programming. Dynamic programming is supported by the dynamic keyword.

The dynamic keyword is used to declare dynamic types. The dynamic types tell the compiler that the object is defined as dynamic and skip type-checking at compiler time, delay type-checking until runtime. All syntaxes are checked and errors are thrown at runtime.

Example

 Live Demo

using System;
namespace DemoDynamicKeyword{
   class Program{
      static void Main(string[] args){
         dynamic MyDynamicVar = 100;
         Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());
         MyDynamicVar = "Hello World!!";
         Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());
         MyDynamicVar = true;
         Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());
         MyDynamicVar = DateTime.Now;
         Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar, MyDynamicVar.GetType());
      }
   }
}

Output

The output of the above example is as follows.

Value: 100, Type: System.Int32
Value: Hello World!!, Type: System.String
Value: True, Type: System.Boolean
Value: 01-01-2014, Type: System.DateTime
raja
Updated on 04-Aug-2020 06:25:55

Advertisements