Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remember to use return value?

Tags:

c#

Sometimes I forget to use the return value when I have to. For example

var s = "foobar";
s.Replace("foo", "notfoo");
// correct: s = s.Replace("foo", "notfoo");

This also applies to my custom value-like classes, for example, where I use fluent x.WithSomething() methods that return new value object instead of modifying x.

One solution would be to use unit tests. However, this is not always applicable. So, how do I force a compiler - or, at least, runtime - error when returned value is not used?

Maybe, there's a ReSharper or VS solution?

UPDATE: OK it is not enforced by language. So null arguments are, but still I can throw exception if argument is null. And ReSharper can warn me about many things that are not enforced by C#. But I see no way to do the same for not-used return value - for those return values that I want to be used.

If not for system functions (like string.Replace), but at least for my own classes - is there any way? Like, returning RequiredReturn<T> or something like this.

UPDATE: what about AOP / PostSharp? If I mark return value or method with [UsageRequired], can I detect somehow using PostSharp that return value was used?

(note the C# tag)

like image 231
queen3 Avatar asked Nov 05 '09 10:11

queen3


3 Answers

If it's really important that you deal with the output value, you could pass the function a value by reference and set that withing the function, rather than returning it.

That way the code calling the function is forced to consider the output value by having to supply it as a parameter at compile time

like image 94
John Sibly Avatar answered Oct 23 '22 15:10

John Sibly


You don't.

It's the same question as asking how do I remember to assign something to my GetSomeStuff() method?

For instance, I keep doing:

GetSomeStuff();

But it should be:

Stuff some = GetSomeStuff();

Just remember. Simple.

On a related note, personally, I think the Replace method should not have been an instance method if it doesn't affect the instance (and yes, I'm aware that strings are immutable). the naming should better reflect we're dealing with an instance method on an immutable object.

Edit: To better reflect what I was trying to say, and work my comment into it as well.

Ah. Just noticed there is an option in Resharper 4.5 to discover 'Unused return values of non-private methods', that may exactly be what you want.

like image 24
Wim Avatar answered Oct 23 '22 16:10

Wim


Use the plugin for Visual Studio, resharper. This plugin tells you on the fly when you are writing dumb code.

like image 35
David Espart Avatar answered Oct 23 '22 16:10

David Espart