Showing warning when function result is not assigned to variable
I have a function that returns a modified copy of the object that was passed to t开发者_运维问答his function. I often do something like this:
obj = obj.Foo(param);
Don't ask why, I simply have to. But sometimes, I (and others) forgot to assign the return value, doing this:
obj.Foo(param);
which repeatedly leads to time-consuming debugging.
Is there any way to show a warning or error every time when the function result is not assigned to a variable? Or any other suggestions on how to solve this issue?
You could use an out parameter, so the call would look like this:
obj.Foo(param, out obj);
You can use Resharper to assist with this issue; you need to decorate your method with the [Pure]
attribute:
[Pure]
public static IList<T> RemoveItem<T>(this IEnumerable<T> thisList, T item)
{
var list = thisList.ToList();
list.Remove(item);
return list;
}
then when you call it without assigning the return value you will see:
The [Pure]
attribute is defined in Resharpers Data Annotations: You need to copy the classes into your project so you can reference them (many very useful other annotations too)
It's totally legal and often desirable to not assign the return parameter so it would be wrong to have a warning for it. Henrik's answer to use an out
parameter is what I'd recommend too to ensure the result is assigned everytime.
you can enable visual studio warings.
you can even customize the rule you want to apply.
you should see warnings in the case you don't assign the function to a variable
you can also decide to treat the waring as errors
Example:
public static class MyClass
{
public static string GetStr()
{
return "";
}
public static void Main()
{
GetStr();
}
}
I can't comment on answers, lacking stackoverflow credits. But I agree with Chris that it's totally legal and often desirable not to assign values returned from a method. It's also occasionally not desirable. e.g.
public static int Square(this int myValue)
{
return myValue * myValue;
}
It's clear that calling this method without assigning it is probably a bug. I think creating a code analysis rule that warned every time you didn't assign a value as Massimiliano suggested would be worse than not having the rule at all. In such cases it would be nice to be able to apply an attribute to the method...
[MustAssign]
public static int Square...
You could create a rule as Massimiliano suggested but only invoke the warning when the method is adorned with the attribute and the value returned from the method is not assigned. Not a trivial exercise though.
精彩评论