Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic, Object, Var

With the inception of the dynamic type and the DLR in .NET 4, I now have 3 options when declaring what I call "open" types:

  • var, locally implicit types to emphasize the 'what' instead of the 'how',
  • object, alias for System.Object, and
  • dynamic, disable compiler checks, adding methods/properties at runtime

While there's a lot written about these out there, nothing I've found puts them together, and I have to confess, it's still a bit fuzzy.

Add to this LINQ, lambda expressions, anonymous types, reflection... and it gets more shaky.

I'd like to see some examples, perhaps contrasting advantages/disadvantages, to help me solidify my grasp of these concepts, as well as help me understand when, where and how I should pick between them.

Thank you!

like image 752
Gustavo Mori Avatar asked Jun 22 '11 07:06

Gustavo Mori


1 Answers

  • Use var to keep your code short and more readable, or when working with anonymous types:

    var dict = new Dictionary<int, List<string>>();
    
    var x = db.Person.Select(p => new { p.Name, p.Age });
    
  • Use dynamic when dynamic binding is useful, or required. Or when you need to decide which method to call based on the runtime type of the object.

  • Use object as little as possible, prefer using specific types or generics. One place where it's useful is when you have object used just for locking:

    object m_lock = new object();
    
    lock (m_lock)
    {
        // do something
    }
    
like image 120
svick Avatar answered Sep 29 '22 10:09

svick