dvdmchl
dvdmchl

Reputation: 1

Object reference not set to an instance of an object

Getting this error on this code:

string pname = null;
pname = ag.FirstOrDefault().arrangement.parent.name;

when calling the line pname = ag.FirstOrDefault.....

The filed parent.name is empty(null), which is fine I want to get an empty(null) string in such case. How can I get rid of the error?

Upvotes: 0

Views: 2271

Answers (4)

Pranay Rana
Pranay Rana

Reputation: 176956

try

var obj = ag.FirstOrDefault();
if( obj !=null)
pname = obj.arrangement.parent.name ?? String.Empty;

or you can try

//This will set the variable to null:
  var obj = ag.FirstOrDefault();
    if( obj !=null)
    pname = Convert.ToString(obj.arrangement.parent.name);

Note : ag.FirstOrDefault().arrangement.parent.name is nullable type

Upvotes: 0

Leons
Leons

Reputation: 2674

You cannot access the properties of a null object. If ag.FirstOrDefault() will return null, then you will not be able to access arrangement.

var temp = ag.FirstOrDefault();
string pname = (temp!= null) ? temp.arrangement.parent.name : null;

You may need to do further null checking.

Upvotes: 0

Security Hound
Security Hound

Reputation: 2547

If the property ag.FirstOrDefault().arrangement.parent.name is null it means the object ag is null also. This is the reason you are getting object reference error.

The answer Leons provided is actually what I was going to suggest. You need to do some research on the problem its one of the simplest thing to avoid ( trying to reference a null object ) in programming.

Upvotes: 0

LukeH
LukeH

Reputation: 269658

Either ag is null, the FirstOrDefault call is returning null, arrangement is null, or parent is null.

Only you are in a position to determine which one of those is actually the culprit.

Upvotes: 6

Related Questions