Asdfg Asdfg - 2 months ago 14
C# Question

Cannot convert lambda expression to type 'object' because it is not a delegate type

I have a base class that has a bool property which looks like this:

public abstract class MyBaseClass
{
public bool InProgress { get; protected set; }
}


I am inheriting it another class from it and trying to add InProgress as a delegate to the dictionary. But it throws me an error. This is how my Derived class looks like:

public abstract class MyClass
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("InProgress", InProgress => base.InProgress = InProgress);

}


This is the error i am getting:


Cannot convert lambda expression to type 'object' because it is not a delegate type


What am i doing wrong here?

Answer

Best would be to have the dictionary strongly typed, but if you assign the lambda to a specific lambda (delegate) first, it should work (because the compiler then knows the delegate format):

        Action<bool> inp = InProgress => base.InProgress = InProgress;
        dict.Add("InProgress", inp);

Or by casting it directly, same effect

       dict.Add("InProgress", (Action<bool>)(InProgress => base.InProgress = InProgress));

Of course having such a dictionary format as object is discussable, since you'll have to know the delegate format to be able to use it.

Comments