Alex Rivera | Logout

C# Compiler Enhancement Suggestion

Asked 2009-03-09T22:30:15.630
13

Imagine someone coding the following:

string s = "SomeString";
s.ToUpper();

We all know that in the example above, the call to the “ToUpper()” method is meaningless because the returned string is not handled at all. But yet, many people make that mistake and spend time trying to troubleshoot what the problem is by asking themselves “Why aren’t the characters on my ‘s’ variable capitalized”????

So wouldn’t it be great if there was an attribute that could be applied to the “ToUpper()” method that would yield a compiler error if the return object is not handled? Something like the following:

[MustHandleReturnValueAttribute]
public string ToUpper()
{
…
}

If order for this code to compile correctly the user would have to handle the return value like this:

string s = "SomeString";
string uppers = s.ToUpper();

I think this would make it crystal clear that you must handle the return value otherwise there is no point on calling that function.

In the case of the string example this may not be a big deal but I can think of other more valid reasons why this would come in handy.

What do you guys think?

Thanks.

Edit
Report

1 Answer

8

Does one call a method for its side-effects, for its return value, or for both? "Pure" functions (which have no effects and only serve to compute a return value) would be good to annotate as such, both to eliminate the type of error you describe, as well as to enable some potential optimizations/analyses. Maybe in another 5 years we'll see this happen.

(Note that the F# compiler will warn any time you implicitly ignore a return value. The 'ignore' function can be used when you want to explicitly ignore it.)

answered 2009-03-09T22:35:32.323

Your Answer