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
}
}
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.
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