Reputation: 520
I want to separate IEnumerable
variables by their types. My code is like this:
if (type is IEnumerable)
{
var listGenericType = type.GetType().GetGenericTypeDefinition().Name;
listGenericType = listGenericType.Substring(0, listGenericType.IndexOf('`'));
if (listGenericType == "List") {
//do something
}
else if (listGenericType == "HashSet") {
//do something
}
}
When I use type.GetType().GetGenericTypeDefinition().Name
, the listGenericType
is like List`1
or HashSet`1
but I want it like List
or HashSet
. Thus, I used Substring
to handle this issue!
Is there anyway to handle this problem without postProcessing string
type? I mean something like below code:
if (type is IEnumerable)
{
var listGenericType = type.GetType().GetGenericTypeDefinitionWithoutAnyNeedForPostProcessing();
if (listGenericType == "List") {
//do something
}
else if (listGenericType == "HashSet") {
//do something
}
}
Upvotes: 5
Views: 276
Reputation: 3845
You don't have to compare it against a string. Since GetGenericTypeDefinition()
returns a type, all you have to do is compare it against a type using the typeof
operator, as such:
if (type is IEnumerable)
{
var listGenericType = type.GetType().GetGenericTypeDefinition();
if (listGenericType == typeof(List<>)) {
//do something
}
else if (listGenericType == typeof(HashShet<>)) {
//do something
}
}
As @nopeflow kindly pointed out below, if your type if not a generic type then GetGenericTypeDefinition()
will throw an InvalidOperationException
. Make sure you account for that.
Upvotes: 5
Reputation: 5600
Assuming you are looking for Generic types only, I believe this might help you out.
List<int> someObject = new List<int>();
Type currentType = someObject.GetType();
if (currentType.IsGenericType)
{
if (currentType.GetGenericTypeDefinition() == typeof(List<>))
{
// Do something
}
else if (currentType.GetGenericTypeDefinition() == typeof(HashSet<>))
{
// Do something else
}
}
Upvotes: 0