Value assigned is not used in any execution path - C# [duplicate]

末鹿安然 提交于 2019-12-13 00:47:46

问题


Resharper is showing this warning: "value assigned is not used in any execution path" when I write the following code:

List<obj> testObj = new List<obj>();
testObj = testMethod();

Here testMethod() returns type List<obj>. However when I directly assign the testMethod() without instantiating it, I don't get the warning.

List<obj> testObj = testMethod();

Forgive me for my ignorance, if I am missing the basics but I'm not following how the compiler allocates memory for testObj without instantiating it.

One of the posts refers to similar question: C# Is this initialiser really redundant? but I don't find any answer to my question, as to where the testObj variable is storing the value it received from testMethod? Unlike primitive data types, 'object types' can store value only after they are instantiated. Please let me know, if I am missing something.


回答1:


You are creating an instance of a List<object> in the first line. And then you throw this object away by assigning the testObj variable another value returned from your method testMethod. This new List<obj>() object is redundant. You effectively creating garbage that Garbage Collector will have to clean at some point.

That's why ReSharper showing you warning.

If you can initialize variable with actual value right in the same line where the variable is defined then do it.

EDIT (assuming we are talking about situation provided in the question):

  1. new operator does not deal with variable itself. It creates a new object in the heap (for reference types).
  2. = operator assigns a value to a variable in the stack. In this case value is a reference to an object in the heap.
  3. There is no difference between assigning a value to a variable returned from a method or an object constructor. Object constructor is actually a method too.
  4. Variable don't need to be initialized before it's possible to assign a value to it. Actually initialization by definition is an assignment of initial value to a variable.


来源:https://stackoverflow.com/questions/33115839/value-assigned-is-not-used-in-any-execution-path-c-sharp

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