Question

I have this code:

foreach (UIElement uiElement in list)
{
    uiElement.SetValue(Grid.ColumnProperty, colunmn++);
    uiElement.SetValue(Grid.RowProperty, _uiRoot.RowDefinitions.Count - 1);
    _uiRoot.Children.Add(uiElement);
}

It runs fine, but Code Contracts is giving me a warning: Possibly calling a method on a null reference, uiElement.

How can uiElement ever be null? The list is a List of UIElements so it should iterate through the list without any nulls.

Was it helpful?

Solution

Because you can put nulls in your list, even though you probably won't

you can do

foreach (UIElement uiElement in list.Where(e => e != null))
{
   uiElement.SetValue(Grid.ColumnProperty, colunmn++);
   uiElement.SetValue(Grid.RowProperty, _uiRoot.RowDefinitions.Count -1);
   _uiRoot.Children.Add(uiElement);
}

OTHER TIPS

A list can contain null references. You can insert null into a list. You can also insert a good reference into a list, then set it to null later. For example, if I have a list of People, I can have the list: "Bob", "Fred". Now I grab Bob from the list, do some stuff, and change it to null. A list contains a list of References not items. So it points to the location where the item was. Now when you iterate through the list, location 0 is now null since the reference where Bob was now contains a null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top