Difference Between Object and Dynamic Keyword In C#.NET

Introduction

Object released initial phase of c# where as Dynamic released in c#(4.0) and .NET framework 4.5. Even though both are looking like similar, but still they have some differences that we will discuss below.
Difference 1

Compiler has very little information about the Object type.
But Compiler do not have any information about the dynamic.

Fig-1

You can see the above Fig (Fig-1)  Compiler ask Object type to cast the object , but in case of Dynamic compiler assign the value without casting .

The above point suggest Compiler do not have any information about the type for Dynamic where as for Object compiler have little information about the Object type.

However if you run the above code shown in fig-1 will through an exception as integer and string addition is not possible. 

Difference 2

Object Introduced when C# 1.0 version released.
Dynamic Introduced when C# 4.0 version released.

Difference 3

Dynamic Convert to object after compilation to MSIL Code, where as object type is the base type.

Conclusion

When there is more casting is used then you should use "Dynamic" over "Object".

My recommendation is to use Object and Dynamic as less as possible because of below reasons.
  • Not compiler friendly.
  • Degrade the performance due to boxing(conversion from value type to object) and unboxing(conversion from object type to value type)


Thanks..........................
Share:

No comments:

Post a Comment

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts