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)
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
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.
Use the plugin for Visual Studio, resharper. This plugin tells you on the fly when you are writing dumb code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With