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.

In C#, object and dynamic are both used to handle variables that can store any type of data, but they have key differences in how they are used and how type checking is performed.

Object

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.

  • Purpose - object is the base type from which all other types, including value types and reference types, derive.
  • Type Checking - Type checking for object variables is performed at compile time.
  • Usage - Use object when you need to store a value of any type and you know the type at compile time. Casting is required to use the stored value in its original type.

Example

object obj = "Hello, World!";
string str = (string)obj; // Requires explicit casting
Console.WriteLine(str);

Dynamic

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.

  • Purpose - dynamic is used to store a value of any type, with type checking deferred until runtime.
  • Type Checking - Type checking for dynamic variables is performed at runtime.
  • Usage - Use dynamic when you need to store a value of any type and you want to bypass compile-time type checking, allowing for more flexible code that adapts at runtime.

Example

dynamic dyn = 123;
Console.WriteLine(dyn + 1); // No casting required, resolved at runtime

Here is a comparison table highlighting the differences between object and dynamic in C#.

Feature Object Dynamic
Type Checking Compile-time Runtime
Casting Requires explicit casting No casting required
Performance Better performance due to compile-time checking Potentially slower due to runtime checking
IntelliSense Full IntelliSense support Limited IntelliSense support
Errors Detected at compile-time Detected at runtime
Usage Scenario Known type at compile-time Unknown or flexible type at runtime
Example Declaration object obj = "Hello"; dynamic dyn = "Hello";
Handling Exceptions Compile-time errors for invalid operations Runtime exceptions for invalid operations

Prev Next