Reputation: 2667
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.
Upvotes: 2
Views: 12752
Reputation: 103338
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();
}
}
Upvotes: 3
Reputation: 62484
public void SetUser(User user)
{
string streetNumber = String.Empty;
if (user!= null
&& user.Address != null
&& user.Address.StreetNo != null)
{
streetNumber = user.Address.StreetNo.ToString();
}
}
Upvotes: 2
Reputation: 18745
if (user != null
&& user.Address != null
&& user.Address.StreetNo != null)
{
// ...
}
Upvotes: 1
Reputation: 52270
Check your stacktrace and:
with an if ... == null then ...
Upvotes: 1
Reputation: 168958
Either user
is null, or user.Address
is null. You need to test them too.
Upvotes: 2