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
, anddynamic
, disable compiler checks, adding methods/properties at runtimeWhile 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!
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With