I’m trying to check if something is an interface and I’m not sure I’m going about it the correct way. I have the underlying interface that I want to check against:
interface IName
{
string Name {get;}
}
I then have a class that implements this interface:
class Person : IName
{
public string Name {get;}
}
I then have another interface:
interface IThing<T>
{
T Thing {get;}
}
I then have another class that implements IThing:
class Teacher : IThing<Person>
{
public Person Thing {get;}
}
What I want to be able to do is this:
Teacher teacher = new Teacher("Math", "John");
if (teacher is IThing<IName>)
{
Console.WriteLine((teacher as IThing<IName>).Thing.Name);
}
This doesn’t work however. I’m pretty sure it can’t figure out that IThing<Person> is an IThing<IName>. How do I accomplish this? I basically have several classes that implement the IThing<BaseClassThatIsIName> so I don’t want to explicitly cast to the type, but rather the interface.
The problem is that you’re specifically trying to see if the teacher implements the
IThing<IName>interface. It doesn’t however, it implements theIThing<Person>interface wherePersonimplements theINameinterface. You’re looking for some covariance here but the way you’ve defined theIThing<>interface doesn’t allow for it. Allow for it:Now the interface will match exact parameter types or more general types. You should be able to do what you want now: