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

3 comments:

  1. 많은 사람들이 많은 베팅 활동을 수행하지만 일부 사람들은 스포츠 게임에 베팅을 설정하는 것을 좋아합니다. 스포츠 도박의 버즈는 최근 순간적으로 증가하고있다. 이 사설토토사이트 사이트를 방문하는 경우,당신은 토토 사이트에 대한 점점 더 많은 세부 사항을 받게됩니다.

    ReplyDelete
  2. I know this is an old post, but IDictionary.ContainsKey seems to be case-sensitive. Is there a way to make it case-insensitive?

    ReplyDelete
  3. I know this is an old post, but IDictionary.ContainsKey seems to be case-sensitive. Is there a way to make it case-insensitive?

    ReplyDelete

Real Time Web Analytics