remove this useless assignment to local variable c#

被刻印的时光 ゝ 提交于 2019-12-11 07:56:31

问题


var  stopFyon = new StopFYON();
IEnumerable<CarOnline> carOnlineData = (IEnumerable<CarOnline>)vehrep.GetCarOnlineDetail(maintainStopFactoryOrderNo.VehicleDetail).Result;

if (carOnlineData.Any())
{
    stopFyon = vehtran.CreateStopFactoryOrderNo(carOnlineData, maintainStopFactoryOrderNo, lastUpdatedBy);
}
else
{
    stopFyon = vehtran.CreateStopFactoryOrderNo(null, maintainStopFactoryOrderNo, lastUpdatedBy);
}
return gen.GetResponse((Int16)ResultCode.Success, (Int16)MsgType.Ok, null, vehrep.StopFactoryOrderNo(stopFyon));

I got warning error when using sonar code analysis:

remove this useless assignment to local variable stopFyon


回答1:


Don't use var:

StopFYON stopFyon;

The reason for the warning is that you initialize the variable with the default constructor(which could theoretically be a very expensive call, at least it's confusing). But this assignment gets overridden in all branches(the if and the else). So it's useless.

If you would use stopFyon before the if the warning would also disappear.




回答2:


The message is pretty straightforward:

IEnumerable<CarOnline> carOnlineData = (IEnumerable<CarOnline>)vehrep.GetCarOnlineDetail(maintainStopFactoryOrderNo.VehicleDetail).Result;

StopFYON stopFyon;

if (carOnlineData.Any())
    stopFyon = vehtran.CreateStopFactoryOrderNo(carOnlineData, maintainStopFactoryOrderNo, lastUpdatedBy);
else
    stopFyon = vehtran.CreateStopFactoryOrderNo(null, maintainStopFactoryOrderNo, lastUpdatedBy);

The first assignment:

var stopFyon = new StopFYON();

is useless since another assignment is performed within the if statement right after.




回答3:


It is working, when I change the code StopFYON stopFyon = null instead of var stopFyon = new StopFYON();



来源:https://stackoverflow.com/questions/47903201/remove-this-useless-assignment-to-local-variable-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!