Home > other >  Check T is IEnumerable
Check T is IEnumerable

Time:10-12

I am using a session extension in asp.net core 6 as below:

public static T? Get<T>(this ISession session, string key)
{
    var value = session.GetString(key);
    return value == null ? default : JsonSerializer.Deserialize<T>(value);
} 

When passing Lists, I'd rather get a new class object instead of default (which is null)

List<SavedQueries> savedQueries = Context.Session.Get<List<SavedQueries>>("SavedQueries");

Here, savedQueries is null, which cause further problems. I am using some temporary workaround here:

if (savedQueries is null) savedQueries = new List<SavedQueries>();

How can I make the extension method aware of IEnumerable and return new T() accordingly? something like we did in older .net versions:

public static T? Get<T>(this ISession session, string key) where T : IEnumerable
    {
        var value = session.GetString(key);
        return value == null ? new T(): JsonSerializer.Deserialize<T>(value);
    } 

Error: Using the generic type 'IEnumerable' requires 1 type arguments

CodePudding user response:

Your where statement should be

where T : System.Collections.IEnumerable , new() 

Or else add a

using System.Collections;

CodePudding user response:

An approach like below should work :

var ienum =typeof(IEnumerable<>);
var isImplemented = typeof(T).GetInterfaces().Any(r=> r.GetGenericTypeDefinition() == ienum))

It basically enlists all the interface implemented loop through generic ones and checks if any of them has a generic definition like IEnumerable<>

CodePudding user response:

Use IsAssignableFrom. You need a new() constraint to create an instance of any enumerable:

public static T? Get<T>(this ISession session, string key) where T: new()
{
    string value = session.GetString(key);
    if (value != null) return value;
    if (typeof(IEnumerable).IsAssignableFrom(typeof(T)))
    {
        return new T();
    }

    return default;
}
  • Related