Is this the right way to use dynamic variables in C#?
I am getting the below error when i try to use LINQ expressions with dynamic variable..
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
dynamic dAnimal = new Animal();
string cc = dAnimal.x;
Animal oAnimal = new Animal();
var test1 = oAnimal.listFood.Where(a => a.foodName == "");
var test2 = dAnimal.listFood.Where(a => a.foodName == "");//Error
}
}
public class Animal
{
public string animalName {get; set;};
public List<Food> listFood;
}
public class Food
{
public string foodName;
}
}
My understanding of the problem is that
dAnimal.listFood
type is unknown at compilation time, becausedAnimal
is dynamic. So compiler can't guarantee, thatlistFood
is IEnumerable and it's item hasfoodName
property. However, if you will use delegate, everylistFood
item will implicitly be casted to type of delegate input parameter (you will still have a problem with collection type).Any way, there is no any need to use
dynamic
in this context.