Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get only the type of Enumerable?

Tags:

c#

ienumerable

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
    }
}
like image 798
Zahra Aminolroaya Avatar asked Oct 28 '15 07:10

Zahra Aminolroaya


1 Answers

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.

like image 143
kkyr Avatar answered Oct 04 '22 00:10

kkyr