1

I have a question about using Entity Framework.

I want to access a property of a model connected with another model. But if "parent" object is Null, the ?? operator does not help.

For example: My Customer model has Company model inside. I want to access Customer.Company.Name property. Where the Customer object is allready null, I get the null object reff error.

Sample of accessing the property on null object

If the object is null I would like it to return "". One solution is to write a loner code like:

(Customer!=null) ? ((Customer.Company!=null) ? Customer.Company.Name ?? "" : "" ) : ""

I know this is not the clean way, but there would be nice if there is a solution like ?? which detects null in parent object, too.

4
  • 3
    C# 6 introduced a ?. operator Commented Mar 8, 2017 at 7:57
  • Your answer for a clean solution is null operator (informit.com/articles/article.aspx?p=2421572). Unfortunately it is available since C# version 6. Otherwise, you have no alternative than what you have already written, that means check every parent explicitly if it is null Commented Mar 8, 2017 at 8:00
  • @jambonick Well, you do have some alternatives. You could write some helper methods that act a bit like '?.', say. Commented Mar 8, 2017 at 8:08
  • Thank you for so quick response! Amazing Commented Mar 8, 2017 at 8:28

1 Answer 1

2

As Lei Yang mentioned in the comments you can write something like

var name = Customer?.Company?.Name;

(If you are using C# 6)

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

5 Comments

This actually opened a whole new chapter in my programming life :) Thank you for this. This kind of propagates null to the last check. Also my first example is kind of dumb, because Name which is of type 'string' is never null if the object exists. So the Name??"" is useless. Firstly I didn't know which version am I using. I read somewhere that C#6 came with .NET4.6 and in my project I am using 4.5.2 and I wasn't sure if it would work. But it does. :) Thank you all very much,
A bit off topic, but since C# 7 is coming today, do we still need to say "if you are on C# 6" - I never saw specifically mentioning C# 5, 4, etc.
I just added that make sure... For example at work some of our older projects are still using .NET4.5.
It comes with VS, not .NET version. C#6 => VS2015, C#7 => VS2017 etc. Anyway.
You're right, I'm sorry. I don't know why I thought it depended on the framework. It's also using VS2013 so that might have confused me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.