Search code examples
c#jsongenericsxamarindefault

generic object creation with type as function parameter in c#


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.


Solution

  • 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

    new constraint (C# Reference)

    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 type T. 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, where E is the enum identifier.
    • struct : The value produced by setting all value type fields to their default value and all reference type fields to null.
    • Nullable type : An instance for which the HasValue property is false and the Value property is undefined.