C# – Cannot use a lambda expression as an argument to a dynamically dispatched operation

Problem

You are trying to use a lambda expression on a dynamic object and get the following compiler error:

Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.

As an example, the following code causes this error:

dynamic people = GetPeople();

foreach (var person in people.Where(person => person.Name.StartsWith("R")))
{
	Console.WriteLine($"Name that starts with R: {person.Name}");
}
Code language: C# (cs)

Solution

Cast the dynamic object to a known type, such as IEnumerable<dynamic>. This is common when you are deserializing JSON to a dynamic object that’s actually a list of objects.

In the example code I am trying to call .Where() on the dynamic object. I know that the object is actually an IEnumerable, otherwise I wouldn’t try to call .Where() on it. However, I don’t know the type it contains – it’s dynamic. Therefore the known type is IEnumerable<dynamic>, and therefore I need to cast my dynamic object to IEnumerable<dynamic>.

dynamic people = GetPeople();

foreach (var person in ((IEnumerable<dynamic>)people).Where(person => person.Name.StartsWith("R")))
{
	Console.WriteLine($"Name that starts with R: {person.Name}");
}
Code language: C# (cs)

6 thoughts on “C# – Cannot use a lambda expression as an argument to a dynamically dispatched operation”

Leave a Comment