3.17.2010

Dynamic + Extension Methods = Fail

I am playing around with dynamics right now working on a solution for a completely different problem.

I discovered a issue I didn’t foresee (and maybe I am doing something wrong).

I use AssertExtensions to make my tests more readable so I created my first extension.

public static class AssertExtensions
{
    public static void ShouldBe<T>(this T actual, T expected)
    {
        Assert.AreEqual(expected, actual);
    }
}

I created a test to ‘get’ a property from a dynamic object.

[TestMethod]
public void should_be_able_to_get_property()
{
    var book = new Book {Title = "Icarus Hunt", Author = "Timothy Zahn"};

    var d = book as dynamic;

    d.Author.ShouldBe("Timothy Zahn");
}

Should work right?

Wrong.

image

Oh noes!

Apparently the RuntimeBinder can’t figure out the extension to string. My solution was to do this:

[TestMethod]
public void should_be_able_to_get_property()
{
    var book = new Book {Title = "Icarus Hunt", Author = "Timothy Zahn"};

    var d = book as dynamic;

    var author = d.Author as string;

    author.ShouldBe("Timothy Zahn");
}

I just found it interesting that it didn’t behave the way I would have expected.

0 comments:

Post a Comment