问题
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):
new
operator does not deal with variable itself. It creates a new object in the heap (for reference types).=
operator assigns a value to a variable in the stack. In this case value is a reference to an object in the heap.- 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.
- 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