Monday, August 24, 2009

C# Dynamic

I have seen a lot around about the new dynamic type and how it works but I haven't found many examples similar to what i would do with it or where I would even use it and how it would help me. So I thought maybe there were others out there like me, thus I put some thought into it this weekend.

Here is a simple example of using dynamic:

static void Main(string[] args)
{
dynamic d = GetSomething();
d.Add(args[1]);
}

static object GetSomething()
{
return (new List<string>());
}

This is late binding which has really been around for years. The big discussion in many meetings prior to .NET was always about the benefits and disadvantages of late binding versus early binding. In other words, the Add method of the generic List<> won't be known till run-time. I can remember spending hours in VB 6 planning for this type of binding and managing potential errors.

I have seen a lot of examples of how to use this with the Microsoft Office tools but i don't use much of the Office tools for what I do, so this is not a real life example. I wanted a good example of how it would benefit me, so I spent some time thinking on this, this weekend. I drove my parents moving truck from V.A. to Florida yesterday so I had some time to contemplate this. Look at this example:

static void Main(string[] args)
{
if (GetSomething() is dynamic)
{
// do something with the Enumeration
}
}

static dynamic GetSomething(string productId)
{
// setup code to retrieve a generic list of custom objects
IEnumerable query = from p in (custom result set).Rows
where p["Some Key"].Value.ToString() == productId
select p;
return query;
}


So how does this help me? The dynamic type behaves like an object. This means that the above expression returns true unless "GetSomething()" returns the value null.

I'm trying to get down to the nitty gritty of this dynamic thing so I will address more later along with some even better examples.

No comments: