public abstract class EntityBase { ... }
public interface IFoobar
{
void Foo(int x)
where T : EntityBase, new();
}
public interface IFoobar<
Just try
void IFoobar.Foo<U>(int x) { Foo(x); }
Of course, that still doesn't guarantee that U
is the same as T
. You can't enforce that at compile-time, because when you're implementing an interface, you must follow its rules -- and IFoobar
doesn't put such a restriction on Foo<T>
, and if you do, you would no longer be implementing the interface (by definition, since you are being stricter, and yet you're claiming that you're not).
You can try checking it at run time instead, although that's somewhat "cheating" (since you're not really conforming to the interface then either).
You can do one of two things:
Do a run-time check and throw an exception:
if (typeof(T) != typeof(U)) throw Exception("Not the same type");
As others have stated, perhaps you need to rethink the way you are designing your interfaces.
The biggest problem is that your interfaces are not well defined, and do not match the intent of your code.
If your T
is not publicly visible on the interface, then external code doesn't even have to know there is a T
. You need to either make methods that receive or return T
, or have some property of type T
, or you should simply get rid of T
entirely, and make your interfaces non-generic.
Once you shore this up, it should become more obvious why you don't need two different interfaces here, and you should no longer have to reconcile them.
If it turns out that you do need a version that takes T
, and a non-T version, then the more idiomatic way to do this is pass around object
instead of T
:
public interface IFoo
{
void DoSomething(object o);
object DoSomethingElse();
}
public interface IFoo<T>
{
void DoSomething(T item);
T DoSomethingElse();
}
See interfaces like IEnumerable
, ICollection
, IList
, etc for examples of this.
But consider carefully. This last design compromise (having both a generic and object version) always leaves something to be desired.
You'll sacrifice one of these: