Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if JValue is null

Why this code doesn't run, I want to check if JSON contains integer for key PurchasedValue or not? () :

public PropertyInfo(Newtonsoft.Json.Linq.JToken jToken)
{
    this.jToken = jToken;
    int PurchasedValue = (int)(jToken["PurchasedValue"].Value ?? 0);
}

the error is :

Error CS0019: Operator `??' cannot be applied to operands of type `method group' and `int' (CS0019) 
like image 757
AVEbrahimi Avatar asked Apr 27 '17 11:04

AVEbrahimi


1 Answers

From my understanding jToken["PurchasedValue"] is a nullable value. You have to use

int PurchasedValue = (int)(jToken["PurchasedValue"]?? 0);

nullableObj.Value can be only used without error only when there is a value for the nullableObj

Otherwise You can use like

int PurchasedValue = jToken["PurchasedValue"].HasValue?jToken["PurchasedValue"].Value: 0;

This May not even need type casting

like image 94
Jins Peter Avatar answered Oct 16 '22 22:10

Jins Peter