C#: Preferred pattern for functions requiring arguments that implement two interfaces
Posted
by JS Bangs
on Stack Overflow
See other posts from Stack Overflow
or by JS Bangs
Published on 2010-04-12T16:54:49Z
Indexed on
2010/04/12
17:02 UTC
Read the original article
Hit count: 268
The argument to my function f()
must implement two different interfaces that are not related to each other by inheritance, IFoo
and IBar
. I know of two different ways of doing this. The first is to declare an empty interface that inherits from both:
public interface IFooBar : IFoo, IBar
{
// nothing to see here
}
public int f(IFooBar arg)
{
// etc.
}
This, of course, requires that the classes declare themselves as implementing IFooBar
rather than IFoo
and IBar
separately.
The second way is to make f()
generic with a constraint:
public int f<T>(T arg) where T : IFoo, IBar
{
// etc.
}
Which of these do you prefer, and why? Are there any non-obvious advantages or disadvantages to each?
© Stack Overflow or respective owner