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 returnT?
and the last line to cast toT?
also:Alternatively, you can check for null and maybe throw an exception or do something else if the return is null:
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 justT
. Also using statement and serializer declaration can be simplified with new syntactic sugar since .net5/c#9