Friday, October 18, 2013

Check Properties of a Dynamic Object in .NET

How can you avoid a RuntimeBinderException when working with dynamics?

In JavaScript, checking if an object implements a property is easy; so why can't it be that easy to check dynamics in C#? Well, it sort of is!* If you are using an ExpandoObject, you need only cast it to a Dictionary and check and see if it contains the desired key.

* Offer only valid with ExpandoObject. **
** See sample code for participating interfaces.***
*** Visit your local Visual Studio installation for details.

JavaScript

test("HasProperties", function() {
    var x = { first: "Tom" };
    ok(x.first);
    ok(!x.last);
});

C#

public class ExpandoObjectTests
{
    [Fact]
    public void HasProperties()
    {
        dynamic x = new ExpandoObject();
        x.First = "Tom";
        var map = x as IDictionary<string, object>;
        Assert.True(map.ContainsKey("First"));
        Assert.False(map.ContainsKey("Last"));
    }
}
Shout it

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics