This question already has answers here:
Closed 13 years ago.
Most of us write conditionals like:
if (resultIndex == 0)
...but occaisionally I come across someone writing them like:
if (0 == resultIndex)
...and interestingly those people have been authors and seemingly pretty hot coders.
So why do some people choose the 'backwards' style? Is there some history behind it? Readabililty?
Duplicate: Why does one often see “null != variable” instead of “variable != null” in C#?.
It is a legacy from C, where a common bug would be to write
if (x = 0) {...}
If you taught yourself to write these tests the other way around, then the compiler would complain when you made the == typo, instead of silently adding a bug.
This has been asked numerous times before though I can't seem to find the Dup.
Essentially, this style is a hangover from C where a common mistake for
if (c == 5) //Comparison
was
if (c = 5) //Assignment
In the latter case, the compile rwould not complain so people wrote it like so to reduce the likelyhood of this happening
if (5 == c)
Because (in C, where most of those programmers probably learned; I can't remember if this holds in C#) if you leave off a = character in the 'regular' style, you'll overwrite the value you are trying to compare (and you'll be checking the boolean value of the assignment). If you do it in the 'backwards' style, you'll get a compiler error.
In C#, integer values are not implicitly casted to boolean, so if (a = 0) yields a compiler error and does not compile. Hence, this practice is outdated and totally unnecesary in C#.
The main reason behind this I believe is to prevent mistakes such as:
if (variable = 0)
Where you assign in the condition instead of comparing.
The reason this would fail the other way around is because you have a constant on your left side of the expression.
So if you were to mistakenly write:
if (0 = variable)
You would get a compilation error from trying to assign something to a constant.
In my opinion this has more in regard to programming style, but still might be a good tip for new programmers. But once you're a little more experienced, errors such as this don't happen and if they do you should be able to track them down pretty easily.
Related
This question already has answers here:
C# conditional AND (&&) OR (||) precedence
(6 answers)
Closed 1 year ago.
if (!d1.x0((long) d1.x1, out d2) || d1.x2 != 0 && d1.x2 != e1.x3 || d1.x4 != x4.None && d1.x4 != e1.x5 || d1.x6 != 0UL && (long) d1.x6 != e1.x6)
I spotted this in production C# code (var names replaced for anonymity) and I cannot understand if that statement can work in C#? or maybe other languages too?
I thought || needs to be explicitly grouped with a () if mixed with &&
If it compiles in C# it works. That doesn't mean it's correct. With your variable-name changes it is https://WorseThanFailure.com - worthy hard to read and reason about.
As you know, the language evaluates && and || operators, absent any parentheses, from left to right, with the same operator precedence. But conditionally! In a && b, if a is false b is not evaluated. A similar rule applies to ||.
So this very well could be correct. If it's in production code, and you're not chasing a bug in this part of the code you'd be wise not to touch it. If you do rewrite it, you must understand the desired application logic completely. And, you must inspect your rewrite very carefully and test the resulting code: this kind of logic is notoriously easy to screw up when you rewrite it.
C# got this && / || stuff from the C language. So did C++, Java, Javascript, and many other languages. It's incredibly useful. Time you spend becoming adept with it is time well spent.
This question already has answers here:
Why does is operator behave like == operator?
(3 answers)
Using "is" keyword with "null" keyword c# 7.0
(2 answers)
Closed 2 years ago.
I was teaching my students how to write a function. I used a simple algorithm to determine if a char value is an actual letter (and not a digit or something else).
So I actually typed what my student said (playing dumb on purpose): "if (letter is 'A') {...}"
To my surprise this didn't cause a compiler error. I added the same check for 'B' and 'C' and my program can now determine that A, B and C are indeed letters.
Why does that work? And WHAT exactly am I comparing here?
I'm not actively using type comparisons, which is what the internet keeps turning up.
I did an additional experiment with other values:
char l = 'A';
if (l is 'A')
{
Console.WriteLine("l 'A'...");
}
if (l is "A")
{
// Doesn't compile.
}
int x = 15;
if (x is 15)
{
Console.WriteLine("X is 15.");
}
if (x is 5.6)
{
// Also doesn't compile.
}
As far as I can tell "is" functions as an extended version of the equality (==) operator that also enforces the same type. But I can't find any documentation on it.
is might have two meanings, depending on which version of C# you have.
In older C# versions, is was short for "is assignable to" or "is assignable from", depending on how you read the code in your head. It wouldn't work for the code in your class because it expects a type on the right-hand side, but I include it here for completeness. It's also useful as an efficient and portable null check, ie variable is object is a better way to write variable != null1.
In newer C# versions, is can also be used for pattern matching. This was introduced in C# 72 and extended in C# 8, with more coming in 9. Specifically, the code in the question creates a Constant Pattern expression.
Here's another fun way to see this work. Coming in C# 9, instead of writing a check like this:
if (!string.IsNullOrEmpty(mystring))
You could instead write3
if (mystring is {Length:>0})
Which is nice because it's shorter and you could make an argument removing the negation makes it easier to understand.4
At least, according to one of the developers on the C# team at Microsoft. But what would he know? He only built the thing.
Really, C# 6 if you count exception filters.
Jared Parsons again.
I'd reject that argument on the grounds any gains in removing the negation are less than the subtlety introduced in how we validate for null. But you could try the argument ;) And before anyone asks, I have no idea at this time how the two options perform.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why does one often see “null != variable” instead of “variable != null” in C#?
This is more a curiosity question, is there any performance difference between the statement.
if(value == null)
and
if(null == value)
is it noticeable, I use c#, PHP & javascript quite often and I remember someone saying if(null == value) was faster, but is it really?
I will soon be starting development on an application that will parse huge quantities of data in the region of Terabytes so even if the performance gain is in the millisecond range it could have an impact. Anyone have any ideas?
I doubt that there's a measurable performance advantage either way. I'll bet the person who told you this didn't have any hard data.
As far as I know, it's a historical artifact, a technique from C and C++ to guard against this mistake:
if (c = null) {
}
The compiler will catch this if you reverse the arguments, since you can't assign something to null.
I profiled both over 100 million iterations.
if(value == null)
-- 6.85175704956 seconds (68.5 nano-seconds each)
if(null == value)
-- 6.75543808937 seconds (67.5 nano-seconds each)
So it's up to you if 1 nanosecond is enough of a gain.
There is absolutely no performance difference to be expected.
The only reason the (ugly) form (if null == value) is used is to avoid a C/C++ specific typo:
if (value = null) // compiles but _assigns_ null to value and always returns false
... // never executed
I think it's fair to expect there will be no difference: it's such a simple case that if there was a difference the compiler would make sure to generate the fastest version anyway.
Yes I also think there will be no difference, but personally I prefer if(value == null)
Optimizations like this will gain you a clock cycle at best (I wouldn't know why though). But most likely if it is any better, then the compiler will optimize it for you.
The reason to put any literal (such as null) first is that you can not accidentally assign the value if you do = instead of ==. I personally do find it less readable though.
I'm not sure if it's faster or not but some languages allow you to assign in an if statement without warning you so if you do:
if (value = null) by mistake you could wipe your variable, whereas the other way around wouldn't cause weird issues further on down the execution path.
What I want to do is be told the type, value (if there is one at compile-time) and other information (I do not know what I need now) of a selection of an expression.
For example, if I have an expression like
int i = unchecked((short)0xFF);
selecting 0xFF will give me (Int32, 255), while selecting ((short)0xFF) will give me (Int16, 255), and selecting i will give me (Int32, 255).
Reason why I want such a feature is to be able to verify my assumptions. It's pretty easy to assume that 0xFF is a byte but it is actually an int. I could of course refer to the C# Language Specifications all the time, but I think it's inefficient to have to refer to it everytime I want to check something out. I could also use something like ANTLR but the learning curve is high.
I do intend to read the entire specs and learn ANTLR and about compilers, but that's for later. Right now I wish to have tools to help me get the job done quickly and accurately.
Another case in point:
int? i = 0x10;
int? j = null;
int x;
x = (i >> 4) ?? -1;//x=1
x = (j >> 4) ?? -1;//x=-1
It may seem easy to you or even natural for the bottom two lines in the code above. (Maybe one should avoid code like these, but that's another story) However, what msdn says about the null-coalescing operator is lacking information to tell me that the above code ((i>>4)??) is legal (yet it is, and it is). I had to dig into grammar in the specs to know what's happening:
null-coalescing-expression
conditional-or-expression
conditional-and-expression
exclusive-or-expression
and-expression
equality-expression
relational-expression
shift-expression
shift-expression right-shift additive-expression
... (and more)
Only after reading so much can I get a satisfactory confirmation that it is valid code and does what I think it does. There should be a much simpler way for the average programmer to verify (not about validity, but whether it behaves as thought or not, and also to satisfy my curiosity) such code without having to dive into that canonical manual. It doesn't necessary have to be a VS plugin. Any alternative that is intuitive to use will do just as well.
Well, I'm not aware of any add-ins that do what you describe - however, there is a trick you can use figure out the type of an expression (but not the compile-time value):
Assign the expression to a var variable, and hover your mouse over the keyword var.
So for example, when you write:
var i = unchecked((short)0xFF);
and then hover your mouse over the keyword var, you get a tooltip that says something like:
Struct System.Int16
Represents a 16-bit signed integer.
This is definitely a bit awkward - since you have to potentially change code to make it work. But in a pinch, it let's you get the compiler to figure out the type of an expression for you.
Keep in mind, this approach doesn't really help you once you start throwing casts into the picture. For instance:
object a = 0xFF;
var z = (string)a; // compiles but fails at runtime!
In the example above, the IDE will dutifully report that the type of var z is System.String - but this is, of course, entirely wrong.
Your question is a little vague on what you are looking for, so I don't know if "improved" intellisense solves it, but I would try the Productivity Power Tools.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have seen different ways of writing an if statement.
Which one do you prefer and why?
Example 1:
if (val % 2 == 1){output = “Number is odd”;}else{output = “Number is even”;}
Example 2:
if (val % 2 == 1)
{
output = “Number is odd”;
}
else
{
output = “Number is even”;
}
Example 3:
if (val % 2 == 1)
output = “Number is odd”;
else
output = “Number is even”;
Example 4:
if (val % 2 == 1){
output = “Number is odd”;
} else {
output = “Number is even”;
}
Similar question:
Why is it considered a bad practice to omit curly braces?
For cases like this, there's also the conditional operator:
output = (val % 2 == 1) ? "Number is odd" : "Number is even";
If you're definitely going to use an "if" I'd use version 2 or version 4, depending on the rest of your bracing style. (At work I use 4; for personal projects I use 2.) The main thing is that there are braces even around single statements.
BTW, for testing parity it's slightly quicker to use:
if ((val & 1) == 1)
Version 2. I always include the brackets because if you ever need to put more than one line under the conditional you won't have to worry about putting the brackets in at a later date. That, and it makes sure that ALL of your if statements have the same structure which helps when you're scanning code for a certain if statement.
I use version 2.
One reason to use curly braces becomes more clear if you don't have an else.
if(SomeCondition)
{
DoSomething();
}
If you then need to add another line of code, you are less likely to have an issue:
if(SomeCondition)
{
DoSomething();
DoSomethingElse();
}
Without the braces you might have done this:
if(SomeCondition)
DoSomething();
DoSomethingElse();
I personally prefer 3. The extra curly braces just add too much unnecessary visual noise and whitespace.
I can somewhat see the reasoning for 2/4 to reduce bugs, but I have personally never had a bug because thinking extra lines were inside an if statement. I do use C# and visual studio so my code always stays pretty well formatted. This could however be a problem if I was a more notepad style programmer.
I prefer #2. Easy readability.
None of the above.
If my execution block only has one line (even if it's a huge for statement) then I don't use braces, but I do indent it, similar to #3
if (num > 3)
print "num is greater than 3";
else
print "num is not greater than 3";
An example with multiple statements that do not need curly braces:
if (num > 3)
for (int i = 0; i < 100)
print i + "\n";
else
print "booya!";
That said, Jon Skeet's response in this question is the best
It is more important to be consistent than to select the best.
These styles have different advantages and drawbacks, but none is as bad as mixing them within a project or even a compilation unit or within a function.
Ternary operator is the obvious choice for this specific code. For simple single statement if/else's that can't be otherwise expressed, I'd prefer a properly indented case 3:
if (val % 2 == 1)
output = “Number is odd”;
else
output = “Number is even”;
I understand the motivation behind "always use braces", but I've personally never been bitten by their omission (OK, once. With a macro.)
From the above styles, I'd pick (2). (4) would be ok if "properly" indented.
(1) I'd attribute to a young developer who hopefully will grow out of "compact code", or someone who can't afford a decent monitor. Still, I'd go with it if it was the local style.
I use version 2.
I agree with the ternary operator. Very under utilized in code that I come across, and I think it is much easier and nicer to read than all the extra brackets and indents it takes to write out an if/else statement.
It's strange that nobody mentioned this:
if ( x == 1) {
...
}
else {
...
}
To me, this is the only correct way, of course :-)
I prefer 4 myself, but I think 2 is definitely good too.
Personally, there are two methods that I find being good-practice:
For if-blocks, there's only this way:
if(...)
{
// ...
}
else if (...)
{
// ...
}
else
{
// ...
}
This is the safest and most comprehensible way to write if-else-blocks.
For one liners (true one liners that are comprehensible on one line), you can use the ternary operator.
var objectInstance = condition ? foo : bar;
// Or the binary operator when dealing with null values
var objectInstance = condition ?? foo;
You shouldn't call methods that do something that do not help the current assignation.
I wouldn't use any other way than those stated above.
Version #2 for me - easiest to see, easiest to read, easy to see where the if starts and ends, same for else, you dont have to worry about putting in brackets if you want to add more than one statement.
I would use them in the following order:
1) the Ternary operator
2) example 3, but indented properly
3) either 2 or 4, they are basically the same. I would go with whatever the general styl was where I worked.
I agree with what jake said about omitting the unnecessary curly braces. I have never caused or seen a bug caused by new code being added and someone thinking they were part of an if statement but they weren't because of the lack of curly braces. If someone ever did do that, I would ridicule them mercilessly.
You'd have to torture me to get me to use number 1.
I'd always use #2. #4 is a truly awful layout and would only be done by someone who believes that a method must be one screen size in length and will do anything to cram it in, rather than refactor the code!!!
Personally I prefer version 2. But since it's only formating it doesn't matter. Use which is best readable for you and your team members!
I use a #2 with a minor change
if (condition1)
{
doStuff();
} else
{
doSomethingElse();
}
Single short statements:
if (condition) output = firstChoice;
else doSomethingElse();
Multiple or long statements
if (condition) {
output = firstChoice;
...
} else {
...
}
using with the braces is suggested, I have seen some issue with the if else statement without braces ,(I don't remember exactly) i.e. Statement under if was not executed, when I added the same with braces then only worked.( Using Visual studio & C#4.0).
Example 2 is without a doubt the least error prone approach. Please see this answer I gave to a similar question for the reason why:
What is the prefered style for single decision and action statements?
Although the Visual Studio default for brace usage is to put braces on a newline (my preferred method), the Framework Design Guidelines book (first edition) by Krzysztof Cwalina and Brad Abrams propose a different convention, example 4, placing the opening brace at the end of a preceding if statement (Page 274). They also state "Avoid omitting braces, even if the language allows it".
Not having the second edition at hand, I couldn't say if these conventions have changed or not.