André Morais
André Morais

Reputation: 34

Create objects Type T in .Net Core

I'm creating a web app in .net core and I'm trying to create a generic way to set and get "objects" from Session. The part of setting and getting I can do, my only problem is that I want to initialize the object if it doesn't exists on the session. The error that I get is that 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'SessionExtensions.CreateObject() Can someone help me? Thanks in the advance :) PS: here is my code:

public static class SessionExtensions
{
    public static void Set<T>(this ISession session, string key, T value)
    {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

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

    public static T CreateObject<T>() where T : new()
    {
        return new T();
    }
}

Upvotes: 0

Views: 5523

Answers (1)

Federico Dipuma
Federico Dipuma

Reputation: 18295

Your CreateObject<T> method restricts T to a type with a parameterless constructor (and, of course, not abstract). For this reason you cannot use this method with a less-restricted T like in your Get<T> or Set<T>.

Either add new() constraint to your Get<T> method or do not use CreateObject<T> and return default(T) from your Get<T> method, which will return null for reference types and the default value for value types.

In your scenario I believe is not necessary at all to return a new object when the key is missing from the session dictionary, it is more reasonable to return the default for that type and handle a cache-miss from the caller:

public static class SessionExtensions
{
    public static void Set<T>(this ISession session, string key, T value)
    {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

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

Calling code:

var obj = session.Get<MyClass>("myKey") ?? new MyClass();

Upvotes: 3

Related Questions