Reputation: 15
private void CheckForNewItems()
{
var items = GetChangedItems();
if (items != null)
{
foreach (var item in items )
{
var itemDB= GetItem(item.id);
if (itemDB!=null)
{
itemDB.somevalue= item.somevalue;
SaveToDatabase(itemDB);
}
}
}
}
I Write alot of code similar to the code above. Is there a smarter way to check for nulls in this scenario? Is "if(item!=null)" effecient? Do i even have to check for nulls?
Regards
Upvotes: 0
Views: 2364
Reputation: 3217
You could use Null propagation. But then your SaveToDatabase Method would have to check for Null itself. It could also use Null propagation
private void CheckForNewItems()
{
var items = GetChangedItems();
if (items != null)
{
foreach (var item in items )
{
var itemDB= GetItem(item.id);
itemDB?.somevalue= item.somevalue;
SaveToDatabase(itemDB);
}
}
}
Have a look at : https://roslyn.codeplex.com/discussions/540883
Upvotes: 0
Reputation: 22038
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.
Upvotes: 5
Reputation: 101681
Create an extension method NullOrEmpty
that checks if the collection is null and returns empty:
public static IEnumerable<T> NullOrEmpty<T>(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
Then use it:
foreach (var item in items.NullOrEmpty())
{
...
}
Upvotes: 4
Reputation: 4033
This is a reasonable solution, there isn't much to be changed. I would only change the first if around to prevent nesting:
private void CheckForNewItems()
{
var items = GetChangedItems();
if (items == null)
{
return;
}
foreach (var item in items )
{
var itemDB= GetItem(item.id);
if (itemDB!=null)
{
itemDB.somevalue= item.somevalue;
SaveToDatabase(itemDB);
}
}
}
Upvotes: 0