0

I've got this code:

if (null == _priceComplianceSummaryList)
{
    _priceComplianceSummaryList = new List<PriceComplianceSummary>();
}

Resharper flags it as an issue, suggesting, "Replace 'if' statement with respective branch" If I acquiesce, the code above changes to:

_priceComplianceSummaryList = new List<PriceComplianceSummary>();

Yet it seems R# is often more the belt-and-suspenders type of "cat," urging me to always check if something is null prior to referencing it. So is this ostensibly reckless behavior on its part really just a matter of efficiency? IOW, does "new List<>" only generate a new list if the istance variable (_priceComplianceSummaryList) is null, without having to explicitly check that?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    "IOW, does `new List<>` only generate a new list if the istance variable is `null`, without having to explicitly check that?" No, it does not. – Logerfo Mar 25 '16 at 23:10
  • 6
    The only reason I can see R# suggesting this is because it can determine that `_priceComplianceSummaryList` is *always* null when you make this check, e.g. you're in a constructor and there's no static initialization of the field, making the check redundant. There is nothing special about the `new` keyword when instantiating a `List` - after the assignment `_priceComplianceSummaryList` will *not* be `null`, and whatever (if any) value it had before, be it `null` or not, it will no longer have. – Preston Guillot Mar 25 '16 at 23:10
  • 2
    Can you show the code where you define this variable? Also, what is the scope of the variable? Please show all the relevant code. – Yacoub Massad Mar 25 '16 at 23:11
  • @YacoubMassad: Now it's right there: var _priceComplianceSummaryList = new List(); So I guess there was no possibility of it being anything but null at that point. – B. Clay Shannon-B. Crow Raven Mar 25 '16 at 23:19

1 Answers1

2

"Replace 'if' statement with respective branch" R# suggestion means that there is no scenarios when your boolean expression returns false. For example,

void SomeMethod(bool firstParam)
{
    var secondParam = true;
    if (firstParam || secondParam)
    {
        Console.WriteLine();
    }
}

This code will refactor by R# because firstParam || secondParam is always true.

Then, your 2 examples of code are not always equivalent, but in your scenario they are.

Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43