C# - Is there a way to have a nullable generic property in a class?

Hi, I’m new to C# and I’m not sure if what I’m trying to achieve is possible. I’m using C# 8.0 in a nullable aware context. Basically, I have a generic result class that I use to communicate between the different layers of my application, and also acts as a result object to be serialized as JSON in response to incoming HTTP requests. The result object has 3 properties: status (required), data (optional), message (optional). In the JSON response, the optional fields translate to null. So I want a way to represent them as null in C# too.

public class ApplicationResult<T> : ApplicationResult
    where T : class
    {
        public T? Data { get; set; }

        private ApplicationResult(ResultStatus status, T? data, string? message = null)
            : base(status, message)
        {
            Data = data;
        }

        public static ApplicationResult<T> Success(T? data)
        {
            return new ApplicationResult<T>(ResultStatus.Success, data);
        }

        public static ApplicationResult<T> Error(T? data, string message)
        {
            return new ApplicationResult<T>(ResultStatus.Error, data, message);
        }
    }

    public class ApplicationResult
    {
        public ResultStatus Status { get; set; }

        public string? Message { get; set; }

        protected ApplicationResult(ResultStatus status, string? message = null)
        {
            Status = status;
            Message = message;
        }
    }

The code works for generic classes but if I want to do var result = ApplicationResult<int>.Success(2), I get an error due to the class constraint. However, without the constraint, I cannot set Data as a nullable property. What I’m trying to achieve is: make Data as generic as possible (reference or value types) with the possibility that it could be null in some cases. Is this possible to do in C#? If not, how can I achieve something similar?

Try wrapping your return type with the Nullable type and see if that will work.

public static ApplicationResult<Nullable<T>> Success(Nullable<T> data)