Reputation: 904
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);
}
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.
Upvotes: 1
Views: 955
Reputation: 904
Thanks for the responses. I ended up creating this function which seems to work and I think is a better approach:
private static T ParseResult<T>(string queryResult) where T : new()
{
try
{
Result<T> res = JsonConvert.DeserializeObject<Result<T>>(queryResult);
if (res.Success == 1)
{
return res.Data;
}
return new T();
}
catch (Exception) {
return new T();
}
}
and
internal class Result<T>
{
[JsonProperty("success")]
public int Success { get; set; }
[JsonProperty("data")]
public T Data { get; set; }
}
Upvotes: 0
Reputation: 81553
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();
}
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 :
0
bool
:false
char
:\0
enum
: The value produced by the expression(E)0
, whereE
is theenum
identifier.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
HasValue
property isfalse
and the Value property is undefined.
Upvotes: 5
Reputation: 772
T
could be a class that does not have a default constructor: in this case new T()
would be an invalid statement.
If you want to return with the default object you can use Activator.CreateInstance
instead of returning default(T)
as below:
return Activator.CreateInstance(typeof(T));
if you want to pass parameters in it, then use as below:
return (T)Activator.CreateInstance(typeof(T), args);
Upvotes: 0