Jonathan Birkholz

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.

1
2
3
4
5
6
7
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.

1
2
3
4
5
6
7
8
9
[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.

Oh noes!

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

1
2
3
4
5
6
7
8
9
10
11
[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.

C#