vendredi 14 juillet 2017

C# is generic type with generic type constraint

Let's asume an interface

interface IOwnedBy<T> where T : IOwner 
{ 
    T Owner { get; }
}

and

interface IOwner 
{ 
    public int Id { get; } 
}

Somewhere in my code, I would like to do the following:

if (obj is OwnedBy<IOwner>) 
{
    DoSomethingWith( obj.Owner.Id );
}

Basically, I want to check whether obj is any OwnedBy implementation. As IOwner is the type constraint of any generic parameter, I thought this one would work. But the condition is never met.

Any way without using alot of reflection?





Aucun commentaire:

Enregistrer un commentaire