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
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With