[SOLVED] C# Object reference not set to an instance of an object

Issue

I have the following code:

public void SetUser(User user)
{
   string streetNumber = "";

   if (user.Address.StreetNo != null)
      streetNumber = user.Address.StreetNo.ToString();
   else
     streetNumber = "";
}

I get the ever popular

Object reference not set to an instance of an object.

issue.

Solution

public void SetUser(User user)
{
   string streetNumber = "";

   if (user != null && user.Address != null && user.Address.StreetNo != null) {
      streetNumber = user.Address.StreetNo.ToString();
   }
}

Taking into account @CKoenig’s suggestion, the following throws an exception if the user or user.Address are null:

public void SetUser(User user)
{

   if (user == null) {
       throw new System.ArgumentNullException("user", "user cannot be null");
   }

   if (user.Address == null) {
       throw new System.ArgumentNullException("Address", "Address cannot be null");
   }
   
   string streetNumber = "";

   if (user.Address.StreetNo != null) {
      streetNumber = user.Address.StreetNo.ToString();
   }
}

Answered By – Curtis

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *