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.
You can do it with a cast:
… 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.