I have declared list as below
List<myList> mylist= new List<myList>();
Here is class for myList
internal class myList
{
public int ID { set; get; }
public string Name { set; get; }
}
Now when adding record inside list there are few null values coming from database in "Name" Field.
mylist.Add(new myList{ ID= (int) item["ID"], Name = item["Name"].ToString()});
I know i can add condition to check like
var Name ="";
if (item["Name"] !=null) {
Name = item["Name"]
}
Then use variable Name
while adding record to list
mylist.Add(new myList{ ID= (int) item["ID"], Name = Name});
is there any other better way?
I suspect you're looking for the null-coalescing operator here to provide a default value if the existing value is a null reference.
// Names changed to look more conventional
people.Add(new Person { Id = (int) item["ID"], Name = (string) item["Name"] ?? "" });
Note the use of a cast rather than a call to ToString()
here - if you believe the execution-time type of a value will be a string reference, a cast is a much clearer indication of that, and it validates that expectation; if you end up with (say) a DateTime
value for some reason, the cast will throw an exception rather than propagating bad data through your system.
See more on this question at Stackoverflow