I'm trying to create a list of non-nullable string values by filtering, but I always end up with a list of nullable strings.
var list = new List<string?> {"Cars", "Audi", "", "1920"};
var list2 = list.Where(p => !string.IsNullOrWhiteSpace(p)).ToList(); // return type is List<string?>
Can you help me understand why it doesn't return list of non-nullable strings.
The type doesn't lose its nullability just because you decided to add only non-
nullitems. After all, nothing is stopping you from addingnulls later.If you want to change its type, either do it when creating the new list (ie, declare the variable explicitly as
List<string>), or tell the compiler that the objects your filter returns are non-null: