Search code examples
c#objectdynamicvar

Difference between Object, Dynamic and Var


I need to know the difference between these three keywords Object , Dynamic and var in C#.

I have seen this link but i don't understand in which case i have to use each one.

Can you explain for me, please, the difference between these keywords ? What are the utilities of each keyword?


Solution

  • Everything is Object because it is a base type for every type in .net environment. Every type inherit from Object in a moment, a simple int variable can be boxed to an object and unboxed as well. For example:

    object a = 10; // int
    object b = new Customer(); // customer object
    object c = new Product(); // product object
    object d = "Jon"; // string
    object e = new { Name = "Felipe", Age = 20 }; // anonymous type
    

    It is the most abstraction for any type and it is a reference type. If you want to get the real type, you need to unbox it (using a conversaion strategy such as methods, casts, etc):

    object a = "Some Text";
    string text = a.ToString();
    
    // call a string method
    text = text.ToUpper();
    
    object i = 10; // declared as object but instance of int
    int intValue = (int) i; //declare as an int ... typed
    

    Dynamic is an implementation of a dynamic aspect in C#, it is not strongly typed. For example:

    dynamic a = new Class();
    a.Age = 18;
    a.Name = "Jon";
    a.Product = new Product();
    
    string name  a.Name; // read a string
    int age = a.Age; // read an int
    string productName = a.Product.Name; // read a property
    a.Product.MoveStock(-1); // call a method from Product property.
    

    var is just a keyword of the C# language that allows you define any object of a type since you initialize it with a value and it will determinate the type from this value, for example:

    var a = 10; // int
    var b = 10d; // double
    var c = "text"; // string
    var d = 10m; // decimal
    var p = new Product(); // Product type
    

    The compiler will check the type of the value you have defined and set it on the object.