In C# it's possible to defined a method parameter with two interface restrictions. This with bounds. For example.
interface IA
{
int A {get;}
}
interface IB
{
int B {get;}
}
void Foo<T>(T param1) where T: IA, IB {}
So two interfaces, and the first parameter (param1) of the method Foo should implement both interfaces.
But is this really useful? AFAIK it's not possible to cast an object to multiple interfaces in C#? Of course a class can implement two interfaces.
Sometimes you have genericized logic which requires functionality from multiple types simultaneously. For example, I once had to perform the same logic on the Button, LinkButton, and ImageButton controls from ASP.NET. They each separately derive from WebControl and implement the IButtonControl interface; there is no base class which unites them.
I needed to wire a handler to the Click event, exposed by IButtonControl, and set a client click handler through the Attributes collection, which is exposed by WebControl. To enable a method which does both, my only choice was multiple type constraints:
private T CreateButton<T>() where T : WebControl, IButtonControl, new()
{
var button = new T();
button.Click += ...;
button.Attributes["onClick"] = ...;
return button;
}
You can certainly assign it to one at a time:
IA asIA = param1;
IB asIB = param1;
Further, you can use it as either, even without those lines (assume these take a IA or IB parameter, respectively)
IAFunc(param1);
IBFunc(param1);
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