[ACCEPTED]-C#:Creating Multicast delegate with boolean return type-delegates

Accepted answer
Score: 37
public delegate bool Foo(DateTime timestamp);

This is how to declare a delegate with the 9 signature you describe. All delegates are 8 potentially multicast, they simply require 7 initialization. Such as:

public bool IsGreaterThanNow(DateTime timestamp)
{
    return DateTime.Now < timestamp;
}

public bool IsLessThanNow(DateTime timestamp)
{
    return DateTime.Now > timestamp;
}

Foo f1 = IsGreaterThanNow;
Foo f2 = IsLessThanNow;
Foo fAll = f1 + f2;

Calling fAll, in this 6 case would call both IsGreaterThanNow() and IsLessThanNow().

What this doesn't 5 do is give you access to each return value. All 4 you get is the last value returned. If 3 you want to retrieve each and every value, you'll 2 have to handle the multicasting manually 1 like so:

List<bool> returnValues = new List<bool>();
foreach(Foo f in fAll.GetInvocationList())
{
    returnValues.Add(f(timestamp));
}
Score: 3
class Test
{
    public delegate bool Sample(DateTime dt);
    static void Main()
    {
        Sample j = A;
        j += B;
        j(DateTime.Now);

    }
    static bool A(DateTime d)
    {
        Console.WriteLine(d);
        return true;
    }
    static bool B(DateTime d)
    {
        Console.WriteLine(d);
        return true;
    }
}

0

Score: 3

Any delegate can be a multicast delegate

delegate bool myDel(DateTime s);
myDel s = someFunc;
s += someOtherFunc;

msdn

A 9 useful property of delegate objects is 8 that they can be assigned to one delegate 7 instance to be multicast using the + operator. A 6 composed delegate calls the two delegates 5 it was composed from. Only delegates of the 4 same type can be composed.

EDIT: A delagate has 3 a method GetInvocationList which returns a list with the 2 attached methods.

Here is a reference about 1 Delegate invocation

foreach(myDel d in s.GetInvocationList())
{
   d();
}
Score: 0

I was stumbling upon the same problem. I 5 searched and found this in msdn.

http://msdn.microsoft.com/en-us/library/2e08f6yc(v=VS.100).aspx

There are 4 two methods on delegates

  • BeginInvoke
  • EndInvoke

The link describes 3 these in detail, with code samples.

We can 2 hook into these methods to handle the return 1 values of the delegates.

Score: 0

In your case , Instead of creating a delegate 2 yourself ,

it is better to use pre-defined 1 delegates in C# such as Func and Predicate :

public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);

and

public delegate bool Predicate<in T>(T obj);

More Related questions