1

I want to add a lambda function to a Func<T>. Furthermore I would like the returned value to be that of the first lambda delegate (I cannot initially change the order the first one will always be applied first). When I try to do this with the += syntax I get the following:

Error 44 Operator '+=' cannot be applied to operands of type 'System.Func<TEntity>' and 'lambda expression'

How can I achieve the above? I would really like to avoid using the traditional delegate syntax if possible.

class Transaction
{
    static Func<TEntity> ifNullInitializeWithThisReturnedObject = () => default(TEntity);

    public static bool IsDirty { get; private set; }

    public init (Func<TEntity> IfNullInitializeWithThisReturnedObject)
    {
         ifNullInitializeWithThisReturnedObject = IfNullInitializeWithThisReturnedObject;
    }
    public void somemethod()
    {
        ifNullInitializeWithThisReturnedObject += () => 
        { 
            IsDirty = true; 
            return default( TEntity ); 
        };
    }
}
nawfal
  • 70,104
  • 56
  • 326
  • 368
Joshua Enfield
  • 17,642
  • 10
  • 51
  • 98

4 Answers4

3

Why not use the traditional delegate syntax, and then get the invocation list explicitly? For example:

delegate int fdelegate();

var f1 = new Func<int>(() => { return 1; });
var f2 = new Func<int>(() => { return 2; });

var f1d = new fdelegate(f1);
var f2d = new fdelegate(f2);
fdelegate f = f1d;
f += f2d;

int returnValue;
bool first = true;
foreach (var x in f.GetInvocationList())
{
    if (first)
    {
        returnValue = ((fdelegate)x)();
        first = false;
    }
    else
    {
        ((fdelegate)x)();
    }
}
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • 2
    Excessive syntax for the declarations there. You can reduce that to `fdelegate f = () => 1; f += () => 2;` – Mark H Jun 30 '11 at 15:39
1

+= is for events. You want a List < Func < TEntity > >. Given such a list, you could do this:

// funcList is an IEnumerable<Func<TEntity>> we got somehow
bool firstTime = true;
TEntity result;
foreach (f in funcList)
{
    if (firstTime)
        result = f();
    else
        f();
    firstTime = false;
}
return result;
n8wrl
  • 19,439
  • 4
  • 63
  • 103
1

It sounds like you're trying to use a lambda as a multicast delegate, which isn't what it is.

See this StackOverlflow question: Use of multicast in C# multicast delegates

I'd advise either go back to using the Delegate syntax like this: http://msdn.microsoft.com/en-us/library/ms173175(v=vs.80).aspx, or use a List<Func<TEntity>>.

Community
  • 1
  • 1
Kilanash
  • 4,479
  • 1
  • 14
  • 11
0

What if you created a collection: List<Func<TEntity>> ?

Jay
  • 6,224
  • 4
  • 20
  • 23