Handling json type which can be null or array in c#

I am getting a response from api in which some attribute are lists, but when they are empty instead of getting an empty lists I receive null.
Now my problem is that i am trying to create a new instance of my model in which I have defined that attribute as string[] but the api call returns that particular attribute as IReadOnlyList.

Example: lets call attribute for listOfNames which can either be null or list containing names; ["henry", "Jack"]. The type of listOfNames is IReadOnlyList.

When I try to create my new instance for example: var newInstance = myModel(listOfName.ToArray()) it works fine when listOfNames is not empty, but when it is null the ToArray() method gives error as it cannot be applied to null.

How can I solve this without having to do if statements check before creating new instance of my model.
Right now I have solved this as

var temp = Array.Empty<string>();
if(listOfNames != null){
temp = listOfNames;
}
var instance = myModel(temp);

Above works fine if it is only one such attribute but now I have multiple such attributes and I dont want to handle each one with if statement.

>Solution :

You can use the null-conditional operator in conjunction with the null-coalescing operator:

var instance = MyModel(listOfNames?.ToArray() ?? Array.Empty<string>());

Leave a Reply