Monday 12 January 2015

C# - Object vs Var vs Dynamic

So right now in C# we have the Object class, and the var and dynamic types. At first look, they all seem to do the same job, but not really.

Then the question is, what is the difference between Object, var and dynamic? And when should we use them?

So here is the answer.

Object

The object class in C# represents the System.Object type, which is the root type in the C# class hierarchy. Generally we use this class when we cannot specify the object type at compile time, which generally happens, when we deal with interoperability.

Let's have an example. The following example explains that the variable amount, of which the type is object, but at run time we can get the actual type of that variable that is stored in the variable.



Let's perform a mathematical operation on it.



Why are we unable to perform a mathematical operation on it and instead get an error message but in the previous example we get the type of Amount as System.Int32. If the amount is a Systme.Int32 type and we can store an integer value in it then why are we unable to apply a simple mathematical operation?

Here is the reason. Actually, an object requires explicit type conversion before it can be used. We can store anything in the object type variable but for performing an operation we must type cast it. Because C# is a statically typed language so it will throw an exception when we start performing any operation on it without proper type casting. 


Var

The var type was introduced in C# 3.0. It is used for implicitly typed local variables and for anonymous types. The var keyword is generally used with LINQ.  click here for more

When we declare a variable as a var type, the variable's type is inferred from the initialization string at compile time.


We cannot change the type of these variables at runtime. If the compiler can't infer the type, it produces a compilation error.



Dynamic

The dynamic type was introduced in C# 4.0. The dynamic type uses System.Object indirectly but it does not require explicit type casting for any operation at runtime, because it identifies the types at runtime only.




In the code above we are assigning various types of values in the variable amount because its type is dynamic and dynamic delays determination of the type until execution. All dynamic types variables enjoy the party at runtime.

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives