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

Asdfg picture Asdfg · Apr 23, 2014 · Viewed 84k times · Source

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

Me.Name picture Me.Name · Apr 23, 2014

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.