Is it possible to use Generic mechanism within function body?
for exammple
if (!(someClass is IClass<T, G> where T : someInterface, G : anotherInterface))
{
return;
}
or do casting like this:
var v = (IClass <T, G> where T : someInterface, G: anotherInterface)something;
You can do this, but you have to make sure your interface is covariant:
By marking the type parameters as
out, you are basically saying “I will only ever get aTor anSout of this interface”. For example,IEnumerable<out T>as you can only get aTout of it, but onlyList<T>because you can put aTinto a list as well as get one out.Having defined your interface as such, an
IClass<string, string>is anIClass<object, object>: you know yourIClass<string, string>will only ever give you astring, but since astringis anobjectthen that’s fine, and if you assign it to anIClass<object, object>you know it will only ever give you anobject.(You can’t do this if you interface allows you to put a
Tor anSinto something. If this was the case, and you assigned yourIClass<string, string>to anIClass<object, object>, you could try to put anintinto it and it would fail, because the underlying class only really accepts astring.)What this then lets you do is
or
and both will work if
somethingis actually an object that implements, say,IClass<string, string>.