Check for null in foreach loop
Just as a slight cosmetic addition to Rune's suggestion, you could create your own extension method:
public static IEnumerable<T> OrEmptyIfNull<T>(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
Then you can write:
foreach (var header in file.Headers.OrEmptyIfNull())
{
}
Change the name according to taste :)
How to avoid null checking before foreach IList
Well, you can try ??
operator:
testList ?? Enumerable.Empty<object>()
we get either testList
itself or an empty IEnumerable<object>
:
IList<object> testList = null;
...
// Or ?? new object[0] - whatever empty collection implementing IEnumerable<object>
foreach (var item in testList ?? Enumerable.Empty<object>())
{
//Do stuff.
}
Is if(items != null) superfluous before foreach(T item in items)?
You still need to check if (items != null) otherwise you will get NullReferenceException. However you can do something like this:
List<string> items = null;
foreach (var item in items ?? new List<string>())
{
item.Dump();
}
but you might check performance of it. So I still prefer having if (items != null) first.
Based on Eric's Lippert suggestion I changed code to:
List<string> items = null;
foreach (var item in items ?? Enumerable.Empty<string>())
{
item.Dump();
}
c# avoid checking for nulls when using iterating over collections
You can do it with some linq:
var items = GetChangedItems();
if (items == null)
return;
var existingItems = items
// create a new call that holds both objects
.Select(i => new { ItemDB = GetItem(i.id), Item = i })
// where the itemdb can be found.
.Where(i => i.ItemDB != null);
foreach (var item in existingItems)
{
item.ItemDB.somevalue= item.Item.somevalue;
SaveToDatabase(item.ItemDB);
}
But.... I think the solution you already had, is more readable for everyone.
Why does .NET foreach loop throw NullRefException when collection is null?
Well, the short answer is "because that's the way the compiler designers designed it." Realistically, though, your collection object is null, so there's no way for the compiler to get the enumerator to loop through the collection.
If you really need to do something like this, try the null coalescing operator:
int[] array = null;
foreach (int i in array ?? Enumerable.Empty<int>())
{
System.Console.WriteLine(string.Format("{0}", i));
}
Null Exception handling in foreach loop
Try below code:
foreach(var x in Lists.Where(x => x.fiels != null))
{
}
How best to null check in for-in loop?
Maybe a method reference in the .forEach() will do the trick for you?
void main() {
people?.forEach(expensiveFuction);
}
void expensiveFuction(Person p) {
print(p.name);
}
EDIT: Another solution might be to provide an empty list, if people is null:
for (var p in people ?? []) {
print(p.name);
}
If people evaluates to null, the empty list will be used and no iteration will run.
Can an item in a foreach be null
Sure, foreach
doesn't skip items that are null
. Then you'd get a NullReferenceException
at the line item.PropertyA = new PropertyADto(valueForPropertyA);
.
Instead you could use
foreach(var item in list.Where(i => i != null))
{
// ...
}
Null check in foreach loop of JArray.Children()
Apparently, Children()
returns a custom JEnumerable
type that is actually a struct, so cannot be null, which makes the null propagation awkward. So you could make this work using your first attempt, with a JToken
in the type parameter (like Johnathan Barclay already suggested):
foreach (JToken item in jArrayJson?.Children() ?? Enumerable.Empty<JToken>())
{
}
Or I tweaked your extension method to work off a JToken
itself:
public static JEnumerable<JToken> ChildrenOrEmptyIfNull(this JToken token)
{
if(token == null)
{
return new JEnumerable<JToken>();
}
return token.Children();
}
which you could use like:
foreach (JToken item in jArrayJson?.ChildrenOrEmptyIfNull())
{
}
Related Topics
MVC Validation Lower/Higher Than Other Value
How to Store and Retrieve Credentials on Windows Using C#
How to Create a File and Any Folders, If the Folders Don't Exist
Log4Net Logging of Two Different Levels to Two Different Appenders for the Same Logger
Ways to Synchronize Interface and Implementation Comments in C#
The JSON Value Could Not Be Converted to System.Int32
Is Graphics.Drawimage Too Slow for Bigger Images
I Have to Access/Commit/Update Svn Repository in Wpf Application Using Svn API or Libraries
Some Help Understanding "Yield"
How to Implement a Singleton in C#
How to Programmatically Limit Bandwidth Usage of My C# Application
C#: How to Convert a List of Objects to a List of a Single Property of That Object
How to Test Private Methods with Nunit
Is There a Complete Iequatable Implementation Reference