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.
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.
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.
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.
A delegate is a reference type that can be used to encapsulate a named or an anonymous method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With