5

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?

katit
  • 17,375
  • 35
  • 128
  • 256
  • 6
    You can return `default(T)` as answered in this post: http://stackoverflow.com/questions/302096/how-can-i-return-null-from-a-generic-method-in-c?rq=1 – mindandmedia Jul 21 '12 at 20:58

1 Answers1

7

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...).

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009