How to ensure/check that List is not null before adding item in C#?
I have come across this situation many times when we need to add a new
item to the list. According to good code practice, we should always check
if list is null before adding new item in the list. Below is the sample to
make my question clear. Here we have a function AddSubject() which adds a
new subject based on some condition. Here we need to check if Subjects
field is null. If null then need to create a new list.
For eg:
var students = new Student(){Name="Raj Roy", Age= 23, Subjects = new
List<string>()};
private void AddSubject(Student stud)
{
if(stud.Age > 18>
stud.Subjects.Add("NewSubjectName");
}
We have two options for checking if the List field is null:
if(stud.Subjects == null)
stud.Subjects = new List<string>();
or
stud.Subjects = stud.Subjects ?? new List<string>();
I follow the second approach.
I wanted the suggestion of you guys about the best approach out of these
two or if there is some other better way.
No comments:
Post a Comment