How can I check whether a string variable is empty or null in C#? [duplicate]
if (string.IsNullOrEmpty(myString)) { // }
if (string.IsNullOrEmpty(myString)) { // }
You can do it using Reflection bool IsAnyNullOrEmpty(object myObject) { foreach(PropertyInfo pi in myObject.GetType().GetProperties()) { if(pi.PropertyType == typeof(string)) { string value = (string)pi.GetValue(myObject); if(string.IsNullOrEmpty(value)) { return true; } } } return false; } Matthew Watson suggested an alternative using LINQ: return myObject.GetType().GetProperties() .Where(pi => pi.PropertyType == typeof(string)) .Select(pi => (string)pi.GetValue(myObject)) .Any(value => string.IsNullOrEmpty(value));
You can use Enumerable.Any: bool isEmpty = !list.Any(); if(isEmpty) { // … } If the list could be null you could use: bool isNullOrEmpty = list?.Any() != true;