Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to chain multiple methods to a delegate in one assignment statement?

I want to chain together two (and possibly more in the future) methods to a delegate and just wondered if there is a way to do this in one assignment statement, e.g.

I have a delegate method signature defined as

public delegate void MaskRequestSection(Request request); 

...and 2 methods that use this signature, namely...

public void MaskCvnSection(Request request)
{
    // do the masking operation
}

public void MaskCardNumberSection(Request request)
{
    // do the masking operation
}

At present, I am using the following to instantiate the delegete, chain the 2 methods to it and then invoke them...

private void HideDetailsInRequest(Request request)
{
    MaskRequestSection maskRequestSection = MaskCvnSection;
    maskRequestSection += MaskCardNumberSection;
    maskRequestSection(request);
}

....I am just curious as to why I can't chain both delegates in one statement like below,

MaskRequestSection maskRequestSection = MaskCardNumberSection+ MaskCvnSection;

...but also if there is another way that it can be done within one declaration. I haven't been able to find anything that specifically addresses this on MSDN, and I'm just asking for my own curiosity.

Thanks in advance.

like image 391
phil Avatar asked Oct 23 '12 07:10

phil


People also ask

Can a delegate point to more than one method?

A delegate is a type safe and object oriented object that can point to another method or multiple methods which can then be invoked later.

Which operator is used to add a method to an existing multicast delegate object?

Multicast delegate The + operator adds a function to the delegate object and the - operator removes an existing function from a delegate object. When the multicast delegate is called, it invokes the delegates in the list, in order. Only delegates of the same type can be combined.

What is delegate in C# with example?

A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered.

Is delegates a reference type in C#?

A delegate is a reference type that can be used to encapsulate a named or an anonymous method.


1 Answers

You can do it with a cast:

var maskRequestSection = (MaskRequestSection) MaskCardNumberSection
       + (MaskRequestSection) MaskCvnSection;

... but you can't do it without one, because the + operator here works on delegates, not method groups. When the compiler sees the binary + operator, it has to work out the type of the expression, and that doesn't take the assignment part into account.

like image 51
Jon Skeet Avatar answered Oct 14 '22 01:10

Jon Skeet