Saturday, February 19, 2011

Dynamic Puzzle in C#

I was designing an API using the dynamic keyword influenced by the ASP.NET MVC router API and I faced a run time error that I could not explain. In the end I turned this into a C# puzzle question.

Step 1

Create a console application and paste this code in the Program.cs namespace.
public class MyClass {

    public static string GetID(dynamic d) {

        return d.ID;
class Program {

    static void Main(string [] args) {

        var o = new { ID = "123" };


Run the application. The application displays 123.

Step 2

Add a new class library project, move the class MyClass in the library. Reference the library. Run the application. An exception will be raise by the line "return d.ID;".

Explain why ?


The watch window tell me that my instance d has an ID property and the exception tell me it does not.

No comments:

Post a Comment