I have a list of items and it is maybe empty or null. I need to check if the list contains any List-item or is empty and if not then add an object to the List in C#?
// I have a list, but sometimes it doesn’t have any data added to it
var myList = new List<object>();
var myList = new List<object>();
// Expression is always false
if (myList == null)
Console.WriteLine(“List is never null”);
if (myList[0] == null)
myList.Add(“new item”);
//Errors encountered: Index was out of range. Must be non-negative and less than the size of the collection.
// Inner Exception says “null”
Check if the list is empty in C#
You can check whether the list is empty or not in many ways.
Example:
Output:
Example:
Output:
Do you find it helpful? Share to Spread Knowledge