C# Is this initialiser really redundant?

后端 未结 6 647
故里飘歌
故里飘歌 2021-01-15 14:40

I have the following line of code:

var dmrReceived = new DownloadMessagesReport();

StyleCop and ReSharper are suggesting I remove the redun

6条回答
  •  感动是毒
    2021-01-15 15:14

    That will only generate an object reference error if dmrReceived is accessed before it is assigned. A lot of the times, the reason for resharper saying that an initializer is redundant is that the variable will always be assigned another value in every single possible execution path.

    i.e.

    DownloadMessagesReport dmrReceived;
    
    ...
    
    if(condition) {
        dmrReceived = new DownloadMessagesReport();
    } else {
        throw new Exception("oh no");
    }
    
    return dmrReceived.SomeProperty;
    

    Accessing SomeProperty is the first place in the code where dmrReceived actually needs to have a value. As follows from the rest of the code, there's no way to get to that line of code without assigning it a value, therefore, the initial value that might have been assigned, would not be used in any execution path, and would thus be redundant.

提交回复
热议问题