Deserialize is giving warning Converting null literal or possible null value to non-nullable type

Viewed 43

I am getting a below warning in visual studio 2022 for line (T)ser.Deserialize(sr) in the below code.

Warning:

Converting null literal or possible null value to non-nullable type.

Code:

public T Deserialize<T>(string input) where T : class
{
    System.Xml.Serialization.XmlSerializer ser = new 
      System.Xml.Serialization.XmlSerializer(typeof(T));

    using (StringReader sr = new StringReader(input))
    {
        return (T)ser.Deserialize(sr);
    }
}

Is there a way to get rid of this warning?

2 Answers

XmlSerializer.Deserialize returns a nullable object so your method should also do that. Change the method to return T? and the last line to cast to T? also:

public T? Deserialize<T>(string input) where T : class
{
    System.Xml.Serialization.XmlSerializer ser = new
      System.Xml.Serialization.XmlSerializer(typeof(T));

    using (StringReader sr = new StringReader(input))
    {
        return (T?)ser.Deserialize(sr);
    }
}

Alternatively, you can check for null and maybe throw an exception or do something else if the return is null:

public T Deserialize<T>(string input) where T : class
{
    System.Xml.Serialization.XmlSerializer ser = new
      System.Xml.Serialization.XmlSerializer(typeof(T));

    using (StringReader sr = new StringReader(input))
    {
        var t = ser.Deserialize(sr);
        if(t == null)
        {
            throw new Exception("It was null, panic!");
        }
        return (T)t;
    }
}

I suppose you are using .net6/c#10, that's a new feature in c#10(also u can see this). Compiler always checking for possible null values. That's why it's giving you these warnings. To simply fix that you can just make method return nullable<T> instead of just T. Also using statement and serializer declaration can be simplified with new syntactic sugar since .net5/c#9

public T? Deserialize<T>(string input) where T : class
{
    System.Xml.Serialization.XmlSerializer ser = new(typeof(T));

    using StringReader sr = new StringReader(input);
    return ser.Deserialize(sr) as T;
}
Related