fsu*_*ser 1 c# generics json default xamarin
I'm trying to create a generic function to parse my json result with Newtonsoft:
private T ParseResult<T>(string queryResult)
{
Result res = JsonConvert.DeserializeObject<Result>(queryResult);
if (res.Success == 1)
{
try
{
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(res.data));
}
catch (Exception)
{
return default(T);
}
}
return default(T);
}
Run Code Online (Sandbox Code Playgroud)
If there is a problem with Success or the parsing I want to return an empty object of whatever T is (currently lists or just custom objects).
My problem is that the current solution is returning null instead of an empty object. How can I achieve that the return value will never be null.
Irregardless of whether this is the right or wrong approach. The problem is default(T) will return the default for the type, for Reference Types that is null. If you want an "empty object" (new object) then you will have to use the new constraint and new it up (instantiate it)
Example
private T ParseResult<T>(string queryResult) where T : new()
{
...
return new T();
}
Run Code Online (Sandbox Code Playgroud)
Note : There are caveats though
The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.
Additional Resources
default value expressions (C# programming guide)
A default value expression
default(T)produces the default value of a typeT. The following table shows which values are produced for various types:
- Any reference type :
null- Numeric value type :
0bool:falsechar:\0enum: The value produced by the expression(E)0, whereEis theenumidentifier.struct: The value produced by setting all value type fields to their default value and all reference type fields tonull.- Nullable type : An instance for which the
HasValueproperty isfalseand the Value property is undefined.