Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Type checking for generics [duplicate]

Suppose I have a class

public class Entity<T> { ... // class definition ... }

And say I have bit of code like:

var a = new Entity<string>();
var b = new Entity<int>();
var c = new Entity<bool>();
var d = new int;
var e = new List<string>();

How do I test that an object is of type "Entity" regardless of the type of T? Such that:

a is Entity    // true
b is Entity    // true
c is Entity    // true
d is Entity    // false
e is Entity    // false
like image 246
Frédéric Jean-Germain Avatar asked Dec 01 '25 14:12

Frédéric Jean-Germain


1 Answers

This works:

public class Entity<T>
{ 
}

static class Program
{
    static void Main(string[] args)
    {
        var a = new Entity<string>();
        var b = new Entity<int>();
        var c = new Entity<Point>();
        var e = 1001;
        var f = new List<int>();

        if (a.IsEntity())
        {
            Debug.WriteLine($"{nameof(a)} is an Entity");
        }
        if (b.IsEntity())
        {
            Debug.WriteLine($"{nameof(b)} is an Entity");
        }
        if (c.IsEntity())
        {
            Debug.WriteLine($"{nameof(c)} is an Entity");
        }
        if (e.IsEntity())
        {
            Debug.WriteLine($"{nameof(e)} is an Entity");
        }
        if (f.IsEntity())
        {
            Debug.WriteLine($"{nameof(f)} is an Entity");
        }
    }

    static bool IsEntity(this object obj)
    {
        var t = obj.GetType();
        if (t.IsGenericType)
        {
            return typeof(Entity<>).IsAssignableFrom(t.GetGenericTypeDefinition());
        }
        return false;
    }
}
like image 169
John Alexiou Avatar answered Dec 03 '25 04:12

John Alexiou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!