Sergio Tapia Sergio Tapia - 25 days ago 8
C# Question

I seem to have fallen into some massive, massive trouble with NullReferenceExceptions

Recently I'm developing a software that parses and displays XML information from a website. Simple enough right?

I'm getting LOADS of NullReferenceExceptions. For example, this method:

private void SetUserFriends(List<Friend> list)
{
int x = 40;
int y = 3;

if (list != null)
{
foreach (Friend friend in list)
{
FriendControl control = new FriendControl();
control.ID = friend.ID;
control.URL = friend.URL;
control.SetID(friend.ID);
control.SetName(friend.Name);
control.SetImage(friend.Photo);

control.Location = new Point(x, y);
panel2.Controls.Add(control);

y = y + control.Height + 4;
}
}
}


I had to wrap an ugly as sin If around the actual foreach loop in order to prevent an exception.

I feel I'm just putting bandaids on a flat tire instead of actually fixing the problem. Is there any way I can tackle this problem? Maybe a book I should read regarding programming patterns or what not?

Really, I'm lost. I'm probably asking the wrong questions.

Answer

It sounds as if you're unsure what to do if you receive bad parameters in your methods. There's nothing inherently wrong with what you're doing now, but the more common pattern is to check parameters in the head of your method, throwing an exception if they're not what you're expecting:

if (list == null)
{
    throw new ArgumentNullException(list);
}

This is a common defensive programming pattern - check to make sure that the data you're provided passes basic sanity checks.

Now, if you're calling this method explicitly yourself, and you're finding this method receiving a null list parameter when you're not expecting it, it's time to look at the logic of the calling method. Myself, I prefer to pass an empty list when I have no elements, as opposed to null, to avoid special cases such as this.