Search code examples
c#json.net

JToken.FromObject on notnull object


I have the following extension method:

public static T FromJson<T>(JToken json) where T : notnull  => json.ToObject<T>();

Upgrading to latest Json.NET I now get:

Possible null reference return.

Considering the template restriction is this error safe to ignore ? that is can I add exclamation mark like this?

public static T FromJson<T>(JToken json) where T : notnull  => json.ToObject<T>()!;

Solution

  • As pointed in above comments by @dbc json.ToObject<T>() can still return null even when T is constraint to notnull

    I ended up with:

    public static T FromJson<T>(JToken json) where T : notnull => json.ToObject<T>() ?? throw new ArgumentException(typeof(T).ToString());