0

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?

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 I would recomend use debuger or divide it into multiple statements.
0

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.

1 Comment

It doesn't necessarily mean ag is null. ag might be null; the output of FirstOrDefault might be null; the arrangement member might be null; the parent member might be null.
0

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.

Comments

0

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

2 Comments

This will throw an exception if ag.FirstOrDefault() return null
The filed parent.name is empty(null) -- this line is written by op anyways i am updating my ans

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.