How can I define that parameter?
You can't, basically. Not in a constructor.
The closest you could come to would be to create a static generic method returning a B:
public static B CreateInstance<T>(T item) where T : A, I2
You can't do this in a constructor because constructors can't be generic.
However, then if you need to store that value, you would need to choose to have a field of type A
or I2
, and cast when you need to.
Of course, you could make B
generic as per Enigmativity's answer - but that may have other implications elsewhere. If you want a non-generic B
, you could potentially have both:
public abstract class B
{
// Common operations which don't depend on the constructor parameter
}
public class B<T> : B where T : A, I2
{
public B(T item)
{
}
}
This starts to get pretty complex, of course.
Alternatively, you could skip compile-time checking, and just check at execution time:
public class B
{
private readonly A item;
public B(A item)
{
if (!(item is I2))
{
throw new ArgumentException("...");
}
this.item = item;
}
}
While compile-time safety is preferable in general, it may be that it's not worth the extra hoops you need to go through in this case. It really depends on what you're doing with the type.