Reputation: 1
IAlarmDevice alarmDevice = null;
if(alarmFlag ==
AlarmFlags.Acknowledge
{
alarmDevice = new
Acknowledged Armed Ice("Alarm1",
alarm.AcknowledgeCycle);
}
else{
alarmDevice = new
ResetAlarmDevice("Alarm1",
alarm.ResetCycle);
}
if(alarmDevice == null)
{
throw new ArgumentException("Could
not create an Alarm device");
}
In the above code, the alarmDevice will get assigned in the "else" block if not the "if" block. In case even after assignment the value of alarmDevice is null( say could not find the alarm with the name passed in the constructor), the null check "if(alarmDevice == null)" will handle it. I don't understand why Sonarqube says that it always evaluates to false? It may evaluate to true in case there is no alarmDevice with the alarm name string passed in the constructor in which case alarmDevice will remain null. What am I missing here? Is it a sonar false positive by any chance?
Upvotes: 0
Views: 3308
Reputation: 77304
If you remove all the noise, this is what your code comes down to:
if(...)
{
alarmDevice = new ...
}
else
{
alarmDevice = new ...
}
There is just no way in C# that alarmDevice
could possibly be null. Constructors cannot return null
in C# and so there is no possibility left to not have an instance assigned to your variable.
Upvotes: 0