Combined null and value check

This code works fine:

policy.ProviderID > 0 ? RefDataSources.LegalBodies.GetDisplayName(policy.ProviderID.Value) : null

but Resharper is complaining that policy.ProviderID.Value needs to be null checked (to prevent an InvalidOperationException).

As far as I am aware the condition will only evaluate to true for a non-null value which is greater than 0 and therefore no further check is required.

Should I be logging this as a bug with JetBrains? Or have I misunderstood something.

Jon Skeet
people
quotationmark

I suspect R# is complaining because it doesn't know that policy.ProviderID will return the same value on both evaluations. Consider:

private readonly int? providerId;

public int? EvilProviderId => DateTime.UtcNow.Second == 0 ? null : providerId;

Now consider your code - the condition could be true because the first call is executed on second 59... but then the clock ticks before the second call, which would then return null, causing a NullReferenceException.

If that is why R# is complaining, just extract a local variable:

int? providerId = policy.ProviderId;
// Use providerId in both cases in your expression

people

See more on this question at Stackoverflow