I have a function to deserialize any type of object that I get from the Api. If there is an error, I want to return a new object of type T.
I tried to do it with return new T()
, but I get the error:
'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method
What's wrong with my code?
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
internal static T DeserializeObject<T>(this JsonSerializer serializer, string value)
{
try
{
using (var stringReader = new StringReader(value))
{
using (var jsonTextReader = new JsonTextReader(stringReader))
{
return (T)serializer.Deserialize(jsonTextReader, typeof(T));
}
}
}
catch {
return GetDefault<T>(); //This line returns the error
}
}
public static T GetDefault<T>() where T : new()
{
if (typeof(IEnumerable).IsAssignableFrom(typeof(T)))
{
return new T();
}
return default(T);
}