jengfad
jengfad

Reputation: 734

Null Propagation - Second null checking

I want to insert another null checking on the theme.VersionStamp. Is there a way that I can insert it inside the SequenceEqual argument?

if (theme.VersionStamp != null)
{ 
    if (!origTheme?.VersionStamp.SequenceEqual(theme.VersionStamp) ?? false)
    {
        throw new TwConcurrencyException();
    }
}

Upvotes: 2

Views: 128

Answers (2)

Julian A
Julian A

Reputation: 344

Unfortunately, adding a null check when passing an argument is not possible.

The shortest you can get would be:

if (theme?.VersionStamp == null || 
    !origTheme?.VersionStamp?.SequenceEqual(theme.VersionStamp) ?? false)
{
    throw new TwConcurrencyException();
}

I wouldn't pass an default argument like Rahul is doing, because if the VersionStamp of the origTheme is equal to a default VersionStamp SequenceEqual would incorrectly return true

Upvotes: 1

Rahul
Rahul

Reputation: 77926

It's not required right since anyways you are making that null check if (theme.VersionStamp != null){ and then proceeding. But you could still check again and pass-in a default argument like

if (!origTheme?.VersionStamp.SequenceEqual(theme.VersionStamp ?? new VersionStamp()) ?? false)

Also, I would extend your first null check to below

if (theme != null && theme.VersionStamp != null)
{ 

Upvotes: 1

Related Questions