0

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;
    }
}
1
  • 1
    you could just cast dAnimal.listFood to IEnumerable<Food> Oct 31, 2014 at 8:11

1 Answer 1

0

My understanding of the problem is that dAnimal.listFood type is unknown at compilation time, because dAnimal is dynamic. So compiler can't guarantee, that listFood is IEnumerable and it's item has foodName property. However, if you will use delegate, every listFood 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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.