0

using sonarqube to analyze my code and being told "'alloc' is null on at least one execution path" for the following code

public RetirementAdvantageProgramSleeveAllocation(VariableDVAPolicy policy, Fund fund)
        : base(policy, fund)
    {
        SleeveAllocation alloc = null;
        if (fund.FundAccountType == FundAccountType.PortfolioChoice)
        {
            alloc = PortfolioChoiceAccountAllocation;
        }
        else if (fund.FundAccountType == FundAccountType.Heritage)
        {
            alloc = HeritageAccountAllocation;
        }
        else if (fund.FundAccountType == FundAccountType.RetirementProtection)
        {
            alloc = RetirementProtectionAccountAllocation;
        }
        alloc.PercentValue = fund.Value;
        alloc.PercentAllocation = fund.Value;
        alloc.Units = 0;
        alloc.Value = 0;
    }

alloc.PercentValue = fund.Value; is where i am getting the Possible System.NullReferenceException however is this a false positive? or do i really need to wrap all of these into a if (alloc == null)

thanks

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
testing
  • 363
  • 1
  • 4
  • 10
  • You only assign value to `alloc` when some if is fulfilled. If none is fulfilled, the object will be null. Accessing `alloc.PercentValue` would generate an error. – asd Apr 30 '19 at 11:26

2 Answers2

1

You've got three conditions - an if and two else if.

If any one of those conditions is met, alloc is assigned a reference.

But what if none of them are met? Then you're attempting to use alloc, but it's null.

The question is what should happen if none of those conditions are true. Do you want to throw an exception, or do you want to assign something else to alloc?

You could do that either in a final else :

else
    // throw an exception or assign something else

or you could add a check at the end:

if (alloc == null) 
    // throw an exception or assign something else

What you're doing might also be better represented as a switch statement, since all three conditions are checking the value of fund.FundAccountType. Technically it's going to do the same as what you're doing, but it makes it more readily apparent that all of the conditions are based on that one value.

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
0

if you need to check string is empty and null then you can use this Styntx string.IsNullOrEmpty(myString))