Question Error object reference not set to an instance of an object

ahmedsalah

Active member
Joined
Sep 26, 2018
Messages
32
Programming Experience
3-5
I work on csharp i get error object reference not set to an instance of an object

code give me error

Error object reference not set to an instance of an object:
var Data = result.items.Select(e => new { PartID = e.create._id, IsUpdated = e.create.error != null && e.create.error.reason !=null && !e.create.error.reason.Contains("document already exists") ? 0 : 1, ErrorStatus = e.create.error == null  | (e.create.error.reason!=null && e.create.error.reason.Contains("document already exists")) ? null : e.create.error.reason }).ToList();




ElasticPartialUpdat.Create.error.get returned null.

so how to solve error please ?
 
Why do you think it should not return null? If you think that there should definitely be a value then you need to actually look at where you expect that value to be set to make sure that it is and, if it's not, see why not. If it's reasonable that it not have a value then you need to allow for that. As you have made no effort to explain what you're actually trying to achieve and only posted one line of code that seems purposely hard to read, it's hard for us to say more.
 
Be careful using the bitwise OR | operator instead of the short circuiting logical OR || operator. Bitwise OR evaluates both predicate then returns; logical OR evaluates the left, then only evaluates the right if it is still undecided (if the left predicate is false)

If e.create.error is null, then e.create.error == null | e.create.error.reason ==null will crash with a NullReferenceException, whereas e.create.error == null || e.create.error.reason ==null will not.

Read up on the null-conditional member/index access operators ?. and ?[] too; they'll potentially clean up this if(a != null && a.b != null && a.b.c != null && ...) you're doing (i.e. if(a?.b?.c?. ... != null))
 
Last edited:

Latest posts

Back
Top Bottom