Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework - casting property on null object doesn't throw an exception?
    text
    copied!<p>I'm reviewing some legacy code and came across a snippet which seems like it will throw unwanted exceptions. In essence the code (an EntityFramework query) looks like the following:</p> <pre><code>var serviceId = (Guid?) person.Services.FirstOrDefault(s =&gt; s.Name == "foo").Id; bool inService = serviceId.HasValue; </code></pre> <p>That is, a <code>person</code> has multiple services assigned to them, and we're returning the first service whose <code>Name</code> is <code>foo</code>. Then, we get the Id property (a Guid) on that <code>Service</code> instance, and cast it to a nullable Guid. Finally, if that nullable Guid has a value, then the person must be in that service.</p> <p>(Note: this is not how I would choose to write the above, it's just what I'm working with)</p> <p>I have a feeling that this code simply throws exceptions when the person does not belong to a service with the name "foo" (or really, any service at all), because the <code>FirstOrDefault</code> invocation will return a <code>null</code> <code>Service</code> instance, and accessing the <code>Id</code> property will just throw an NPE.</p> <p>I asked the original developer about this snippet, and I was told that doing the following:</p> <pre><code>(T?) entity.&lt;non-existent entity&gt;.SomeProperty </code></pre> <p>Will simply return a null object, instead of throwing an NPE. Also, this type of "safe null handling" occurs with Entity Framework queries.</p> <p>This seems incredibly counter-intuitive, and doesn't even feel like it should be possible. I tried researching this, but I haven't found anything along those lines. Does anyone have any experience with this? I'm 100% happy to find out that I'm wrong and to learn something new, but it does not feel correct to me.</p> <p><em>As an addendum, I did try running the query above in Linqpad by using the EntityFramework connection, and I did indeed generate an NPE when trying to access the null objects property</em> </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload