Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Passing Anonymous Types with Dynamic Lists

0.00/5 (No votes)
1 Oct 2013 1  
With the dynamic keyword C# is one step ahead of me allowing a future of amazing code determined by an unlimited number of factors at runtime.

Recently I was rewriting a function with a large method signature which took several arrays as parameters.  As you might guess, the index across these arrays was assumed to be the same which is error-prone.  I thought we should really encapsulate all this information in to a class or struct and pass in a single list instead.  Then I stopped myself as there was no use for this class beyond this one-time call to another function.

Then I thought, I know, I could use an anonymous type instead.

var datum = new { a = myData.a, b = myData.b, /* c, d, ..., */ z = myData.z };

This seems like a reasonable approach and exactly what throw-away anonymous types are for.  Then I tried to add this to a list.  Hmm, with a little creativity I was able to overcome this… except it only worked within the scope of the same function.  Well, I could have passed a list of objects, but what would I cast them to?

I really thought I’d have to cave in and just create the new class but then there was one option I hadn’t considered: dynamic.  Like JavaScript, this frees you from the restriction of static typing which was inhibiting a simple notion to pass a list of anonymous types to another function.  Now our list definition looks like this:

var data = new List<dynamic>();

Now this means I could really add in anything and its evaluation will be resolved at runtime.  So we’re finally free to use our anonymous class however we want.  We could even code access to properties which we aren’t supplying and code will compile (however you’ll get a nasty surprise at runtime).

protected void Bob()
{
    List<dynamic> data = new List<dynamic>();

    //
    //Assume lots of processing to build up all these arguments
    //
    data.Add(new { a = 1, b = "test" });

    Fred(data);
}

private void Fred(List<dynamic> data)
{
    //Fred processing logic
    foreach (var datum in data)
    {
        Trace.WriteLine(String.Format("{0}: {1}", datum.a, datum.b));
    }
}

The more evolved my client coding becomes the more restraining statically typed languages can feel.  With the dynamic keyword C# is one step ahead of me allowing a future of amazing code determined by an unlimited number of factors at runtime.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here