How to get only Enumerable type?

I want to highlight IEnumerable variables by their types. My code is as follows:

 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 , listGenericType is similar to List`1 or HashSet`1 , but I want it to be like List or HashSet . So I used Substring to solve this problem!

Is there a way to handle this problem without the postProcessing string type? I mean something like the code below:

 if (type is IEnumerable) { var listGenericType = type.GetType().GetGenericTypeDefinitionWithoutAnyNeedForPostProcessing(); if (listGenericType == "List") { //do something } else if (listGenericType == "HashSet") { //do something } } 
+5
source share
2 answers

You do not need to compare it with a string. Since GetGenericTypeDefinition() returns a type , you need to compare it with the 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 consider this.

+5
source

Assuming you're only looking for generic types, I believe this may help you.

  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 } } 
0
source

Source: https://habr.com/ru/post/1234669/


All Articles