1

When i run the following code :

var aList = new List<string>{"a", "b", "c"};
dynamic a = aList.Where(item => item.StartsWith("a"));
dynamic b = a.Count();

Microsoft.CSharp.RuntimeBinder.RunTimeBinderException raises.

But when I write a code snippet like this:

public interface IInterface
{
}

public class InterfaceImplementor:IInterface
{
    public int ID = 10;
    public static IInterface Execute()
    {
        return new InterfaceImplementor();
    }
}

public class MyClass
{
    public static void Main()
    {
        dynamic x = InterfaceImplementor.Execute();
        Console.WriteLine(x.ID);
    }
}

it's work.

Why first code snippet doesn't work?

1

2 Answers 2

1

Because the Count method is an extension method on IEnumerable<T> (Once you call Where, you don't have a list anymore, but an IEnumerable<T>). Extension methods don't work with dynamic types (at least in C#4.0).

Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not currently kept as part of the payload.

Will the dynamic keyword in C#4 support extension methods?

Sign up to request clarification or add additional context in comments.

Comments

0

Extension methods are syntactic sugar that allow you to call a static method as if it was a real method. The compiler uses imported namespaces to resolve the correct extension method and that is information the runtime doesn't have. You can still use the extension methods, you just have to call them directly in their static method form like below.

var aList = new List<string>{"a", "b", "c"};
dynamic a = aList.Where(item => item.StartsWith("a"));
dynamic b = Enumerable.Count(a);

1 Comment

your answer is true but finding the static class which contains definition for extension methods is so hard. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.