C# - Difference Between Object and Dynamic


There are many different datatypes available in C#, and you can declare a variable type for a particular datatype, such as int, string, or bool. C# is rich in data type. It includes several datatypes like Object and Dynamic that allow you to store data of any type without regard to its exact data type. The type keyword Object was introduced with C# 1.0 and the type Dynamic was introduced in C# 4.0 ( .NET 4.0 with Visual Studio 2010).

Let us see the difference between Object and Dynamic.

1. Object keyword.

The object was introduced in C# 1.0. It can store any type of value because it is the base class for all types in .Net Framework. You need to cast the object variable to the original type to use it. You need to be very careful while using objects because it will create problems at runtime if it is not able to convert to a specific type while being typecast.

Example

object myobject = 10;
myobject = test + 10; // Compile time error
myobject = "hello"; // No error, Need Boxing here

2. Dynamic keyword

It was introduced in C# 4.0. It can store any type of value, and the type of the variable is unknown until runtime. so it will not support IntelliSense. It's not mandatory to initialise at declaration time. Dynamic types can be passed method parameters.

Example

dynamic myobject = 10; 
myobject = test + 10; // No error
myobject = "hello"; // No error, neither compile time nor run time

Difference between Object and Dynamic type

S.No. Object Dynamic
1 The object was introduced with C# 1.0 Dynamic was introduced with C# 4.0
2 The Compiler has little information about the type. It's not compiler safe. The compiler doesn't have any information about the type of variable.
Need to cast the object variable to the original type to use it. Casting is not required.
4 No need to initialize at the time of declaration.
e.g - object str;
No need to initialize at the time of declaration.
e.g - dynamic str;
5 It can store any kind of value because the object is the base class of all type in .NET framework. It can store any type of value, and the type of the variable is unknown until runtime.

Prev Next

Top Articles

  1. Why use C#
  2. How to use comment in C#
  3. How to use variables in C#
  4. How to use keywords in C#