Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading