Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Is operator for Generic Types with inheritance

I have a problem with the is operator comparing generic types.

 public interface ISomeInterface<T> where T : SomeBaseClass{
 }

 public class SomeClass : SomeBaseClass{
 }

Now we want to check the type with is operator. We have an instance of a class implementing interface ISomeInterface.

Unfortunatly we are facing following problem:

 // someObject is an Instance of a class implementing interface ISomeInterface<SomeClass>
 bool isSomeBaseClass = someObject is ISomeInterface<SomeBaseClass>; // false
 bool isSomeClass = someObject is ISomeInterface<SomeClass>; // true

Is it possible to check a variable generic type?

Thanks in advance, Tobi

like image 240
Tobias Avatar asked Dec 05 '22 15:12

Tobias


1 Answers

This is called generic covariance and is supported in C# 4.0. You could mark the generic T parameter with the out keyword:

public interface ISomeInterface<out T> where T : SomeBaseClass

This has a limitation though. The T parameter can only appear as return type of the methods in the interface.

Eric Lippert has a series of blog posts on this subject that I invite you to read.

like image 76
Darin Dimitrov Avatar answered Dec 10 '22 10:12

Darin Dimitrov