Reputation: 468
I have the following generic method:
protected IEnumerable<T> GetAnimals<T>() where T : Animal
{
// code
}
I may call this method using GetAnimals<Dog>()
or GetAnimals<Cat>()
where the Dog and Cat classes inherit from Animal
.
What I need is to get the typeof(T)
to find that the current method is executing with Dog
or Cat
. I've tried so far:
protected IEnumerable<T> GetAnimals<T>() where T : Animal
{
bool isDog = typeof(T) is Dog ? true : false;
}
This typeof
returns Animal
and not Cat
or Dog
, so this is my issue.
One solution would be to create a method in Animal
like WhatIAm()
and implement it in Dog as return typeof(Dog)
but I believe this is a bad solution.
Any advice?
Upvotes: 0
Views: 66
Reputation: 156978
First, if you need a type check inside your generic method, maybe you are having the wrong approach / design. Generally this is considered bad design.
The actual solution to your problem:
bool isDog = typeof(T) == typeof(Dog);
Note that T
must match Dog
exact. Classes deriving from Dog
are excluded.
A better approach might be:
bool isDog = typeof(Dog).IsAssignableFrom(typeof(T));
Also, you don't need the ternary operator.
Upvotes: 5
Reputation: 101681
You can compare the types directly
bool isDog = typeof(T) == typeof(Dog) ? true : false;
typeof(T)
doesn't return Animal
, it returns a type instance. is
operator compares if the Type
is compatible with Dog
which is not because there is no relationship between Dog and type.
Upvotes: 2