Darren Cook
Darren Cook

Reputation: 28928

Why didn't my OrderBy bug give a compiler warning?

I had this code to sort my Array, and I just realized sorting wasn't working:

if(desc)items.OrderByDescending(x=>x.ExpirationDate);
else items.OrderBy(x=>x.ExpirationDate);

Correct code is:

if(desc)items=items.OrderByDescending(x=>x.ExpirationDate).ToArray();
else items=items.OrderBy(x=>x.ExpirationDate).ToArray();

But why did the compiler (I'm using both Mono and Visual C# 2010) not give me an error, or even a warning? Am I missing some setting, or is it simply impossible for a C# compiler to realize my original code was useless? If the latter, are there any lint tools that will look for specific mistakes like this, that I could add to my compiles?

Upvotes: 2

Views: 71

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

It is perfectly valid to call functions and ignore results. Compiler does not know if particular function is pure or have side effect.

I don't think there is error/warning in such case.

Sample of function call that commonly called with ignoring result: Dictionary.Remove - it actually returns true/false unlike pretty much all other Dictionary/List functions.

Upvotes: 7

sa_ddam213
sa_ddam213

Reputation: 43596

Because its not an error, The compiler wont care if you dont use the returned value.

If you want additional warnings to tell you about things like this have a look at JetBrains - ReShaper

Upvotes: 5

Related Questions