Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return null from generic function? [duplicate]

Tags:

c#

.net

generics

I have function like this:

private T DeserializeStream<T>(Stream data) where T : IExtensible
    {
        try
        {
            var returnObject = Serializer.Deserialize<T>(data);
            return returnObject;
        }
        catch (Exception ex)
        {
            this.LoggerService.Log(this.AccountId, ex);
        }

        return null;
    }

Everything is good, except that it complains about return null; part

Cannot convert expression type 'null' to type 'T'

How do I return null from function like this?

like image 946
katit Avatar asked Jul 21 '12 20:07

katit


1 Answers

You can add a generic constraint that T is a class (as structures are value types and cannot be null).

private T DeserializeStream<T>(Stream data) where T : class, IExtensible

As @mindandmedia commented, an alternative is to return the default of T - this will allow it to work on value types (such a Nullable<T>, int32 etc...).

like image 186
Oded Avatar answered Oct 19 '22 02:10

Oded