I am currently studying the conditional constructions. Correct me if I am wrong but else if and else(if(){}) is the same thing... Example:
a=5;
if(a==6)
{
Console.WriteLine("Variable 'a' is 6");
}
else if(a==5)
{
Console.WriteLine("Variable 'a' is 5");
}
And
a=5;
if(a==6)
{
Console.WriteLine("Variable 'a' is 6");
}
else
{
if(a==5)
{
Console.WriteLine("Variable 'a' is 5");
}
}
Are these things the same? And if yes why does else if exist if I can write it the "second way"(the second example that I wrote)?
Yes, these are effectively identical.
The reason the "else if" statement exists is to make cleaner code when there are many conditions to test for. For example:
if (a==b) {
//blah
} else if (a==c) {
//blah
} else if (a==d) {
//blah
} else if (a==e) {
//blah
}
is much cleaner than the nested approach
if (a==b) {
//blah
} else {
if (a==c) {
//blah
} else {
if (a==d) {
//blah
} else {
if (a==e) {
//blah
}
}
}
}
why does else if exist
It doesn't. It's not a keyword or construct on its own. Your two examples are identical except that in the second case you've added some superfluous braces and whitespace into the code.
if and else are both simply followed by a single statement. In your first example the statement following the else is:
if(a==5)
{
Console.WriteLine("Variable 'a' is 5");
}
The second example just wraps that same statement in braces, and adds a new line at the start. The new line is ignored, so it doesn't change the semantics, and as the code is already a single statement, wrapping it in braces doesn't change it in any way.
Strictly speaking, there is no such thing as an else if statement. An "else if" is actually just in essence an else with a single line body that happens to be the start of an entirely separate if statement. You can visualize it like this:
var a = 5;
// This if uses a single line
if (a == 6) DoSomething();
// This else is a single line that is also a single-line if
else if (a == 4) DoAnotherThing();
// This else uses a single line as well, but is referring instead to the second if
else DoSomethingElse();
The above script is identical to the following:
if (a == 6)
{
DoSomething();
}
else
{
if (a == 4)
{
DoAnotherThing();
}
else
{
DoSomethingElse();
}
}
Or even this:
if (a == 6)
DoSomething();
else
if (a == 4)
DoAnotherThing();
else
DoSomethingElse();
The reason that it is written as else if so commonly is because it compliments the logical flow of the code. That, and it just looks so much prettier.
Mostly it makes the code cleaner, easier to read, makes indenting better, particularly if you have any conventions on character length of rows (and if you don't then you've got thirty indents in a big if statement, such a pain to read). It also saves space, a few extra characters and indents across thousands of lines may not be much, but why use it if you don't have to. When the code compiles they will pretty much be the exact same in the DLLs anyways.
Related
I am running through CodeEasy.net's c# program and I have stumbled across a problem I am struggling with. I don't understand why this does not pass.
Write a program that reads from the console one char using
Console.Read() and Convert.ToChar(...) methods. After this, the
program should output "Digit" "Letter" or "Not a digit and not a
letter" to the screen, depending on what the character is.
I have tried int charCode = int.Parse(Console.ReadLine()); as well instead of int charCode = Console.Read(); but nothing seems to work. It keeps giving me the first "if" and last "else" result, but only one of these should print so it is very confusing.
Here is my code so far:
int charCode = Console.Read();
char theRealChar = Convert.ToChar(charCode);
if (char.IsDigit(theRealChar))
{
Console.WriteLine("Digit");
}
if (char.IsLetter(theRealChar))
{
Console.WriteLine("Letter");
}
else
{
Console.WriteLine("Not a digit and not a letter");
}
Any help in making me understand this is much appreciated!
Your else statement is only associated with the second if statement. You've effectively got:
if (firstCondition)
{
// Stuff
}
// You could have unrelated code here
if (secondCondition)
{
// Stuff
}
else
{
// This will execute any time secondCondition isn't true, regardless of firstCondition
}
If you only want it to execute if neither of the earlier if statements, you need the second one to be else if:
if (char.IsDigit(theRealChar))
{
Console.WriteLine("Digit");
}
// Only check this if the first condition isn't met
else if (char.IsLetter(theRealChar))
{
Console.WriteLine("Letter");
}
// Only execute this at all if neither of the above conditions is met
else
{
Console.WriteLine("Not a digit and not a letter");
}
Seems to work fine once you add a missing else before the second if block.
if (char.IsDigit(theRealChar))
{
Console.WriteLine("Digit");
}
else if (char.IsLetter(theRealChar))
{
Console.WriteLine("Letter");
}
else
{
Console.WriteLine("Not a digit and not a letter");
}
SE,
I'm used to Java syntax and have recently had to switch to C# at work. I'm a little confused on why a one of the if/then/else statements I've been writing haven't been working as expected, and was wondering if someone would be able to tell me a bit about the details of the syntax for why this isn't behaving as expected.
Take:
if (salePredicate != null)
if (!salePredicate.Invoke(s))
continue;
else
_sales.Add(s);
In this block, the else statement isn't reached when salePredicate is null. However,
if (salePredicate != null) {
if (!salePredicate.Invoke(s))
continue;
} else
_sales.Add(s);
will reach the else statement. Why isn't the first statement valid?
(P.S., I know the following is an option)
if (salePredicate == null ||
salePredicate.Invoke(s))
_sales.Add(s);
Update:
Statement 1 is really:
if (salePredicate != null)
if (!salePredicate.Invoke(s))
continue;
else
_sales.Add(s);
Use braces, kiddos.
Because the indentation is ignored. It sees the else as being paired with your nested if.
The compiler is associating the else statement with the second if but what you really want is to have it associate with the first one.
if (salePredicate != null)
if (!salePredicate.Invoke(s))
continue;
else
_sales.Add(s);
You can use braces to correct the problem:
if (salePredicate != null)
{
if (!salePredicate.Invoke(s))
{
continue;
}
}
else
{
_sales.Add(s);
}
It is because of this common pitfall that many people recommend that you always use braces, even if they're gratuitous.
Why isn't the first statement valid?
Because the else refers to the second if, not the first one. The whitespace that you've subtracted won't make any difference (since whitespace is not significant in this context), and is actually misleading, since it doesn't reflect the actual meaning of the code.
Most "best practice" practitioners will tell you that omitting the usual braces in this fashion is a bad practice, and this is one of the reasons why.
C# is not python, the compiler doesn't look at your indentation to determine meaning.
You wrote
if (salePredicate != null)
if (!salePredicate.Invoke(s))
continue;
else
_sales.Add(s);
But the compiler treated it as
if (salePredicate != null)
if (!salePredicate.Invoke(s))
continue;
else
_sales.Add(s);
You could have avoided that by "correct" usage of braces ("correct", because even if you memorize the syntax, other developers could get confused when reading your code. Always use braces with nested if/else):
if (salePredicate != null) {
if (!salePredicate.Invoke(s))
continue;
}
else {
_sales.Add(s);
}
Really, I am surprised you didn't run into this in Java as well, because the rules for if/else are essentially the same.
An inner statement will only be evaluated if the outer statement evaluates to true. In this case, second if and the else statements are both nested within the first if statement. You don't have to... but I highly suggest you start using curly braces for your statements, to avoid confusion and bugs.
I believe The first block you mentioned, does not work the way you expected in java either.
The compiler will see that as:
if (salePredicate != null)
{
if (!salePredicate.Invoke(s))
{
continue;
}
else
{
_sales.Add(s);
}
}
You need to explicitly put the blocks to prevent misunderstanding.
Resharper is telling me that the 'else' in this code is redundant:
if(a)
{
//Do Something
}
else if(b)
{
//Do Something
}
The else does not seem redundant because the else keeps b from being evaluated if a is true. The extra overhead is small if b is a variable, but b could also be an expression.
Is this correct?
It's redundant if you have a some sort of break, continue, return, or throw statement (or even a goto) inside the first if-block that always causes execution to branch outside the current block:
if(a)
{
return 0;
}
else if(b)
{
return 1;
}
In this case, if the code enters the first block, there's no way it will enter the second block, so it's equivalent to:
if(a)
{
return 0;
}
if(b)
{
return 1;
}
You are right in this case, but this is the reason I think they had it to begin with:
Certain if-else conditions can have their else clause removed. Consider the following method:
public int Sign(double d)
{
if (d > 0.0)
return 1;
else
return -1;
}
In the above, the else statement can be safely removed because its if clause returns from the method. Thus, even without the else, there’s no way you’ll be able to proceed past the if clause body.
It doesn't appear redundant to me. Removing the else would result in different program flow if both a and b are true.
Switch case statements are good to replace nested if statements if we have the same condition but different criteria. But what is a good approach if those nested if statements all have different and unique conditions? Do I have any alternate options to replace a dozen if else statements nested inside each other?
Sample Code:
Note: I know this is extremely unreadable - which is the whole point.
Note: All conditions are unique.
...
if (condition) {
// do A
} else {
if (condition) {
// do B
if (condition) {
if (condition) {
if (condition) {
// do C
if (condition) {
// do D
if (condition) {
// do E
} else {
if (condition) {
// do F
}
}
}
}
if (condition) {
// do G
if (condition) {
// do H
if (condition) {
// do I
} else {
// do J
}
}
}
}
}
}
The best approach in this case is to chop up the thing into appropriately named separate methods.
I had to check this was Stackoverflow not DailyWTF when I saw the code!!
The solution is to change the architecture and use interfaces and polymorphism to get around all the conditions. However that maybe a huge job and out of the scope of an acceptable answer, so I will recommend another way you can kinda use Switch statements with unique conditions:
[Flags]
public enum FilterFlagEnum
{
None = 0,
Condition1 = 1,
Condition2 = 2,
Condition3 = 4,
Condition4 = 8,
Condition5 = 16,
Condition6 = 32,
Condition7 = 64
};
public void foo(FilterFlagEnum filterFlags = 0)
{
if ((filterFlags & FilterFlagEnum.Condition1) == FilterFlagEnum.Condition1)
{
//do this
}
if ((filterFlags & FilterFlagEnum.Condition2) == FilterFlagEnum.Condition2)
{
//do this
}
}
foo(FilterFlagEnum.Condition1 | FilterFlagEnum.Condition2);
#Tar suggested one way of looking at it. Another might be.
Invert it.
if (myObject.HasThing1)
{
if(myObject.HasThing2)
{
DoThing1();
}
else
{
DoThing2();
}
}
else
{
DoThing3();
}
could be
DoThing1(myObject.HasThing1);
DoThing2(myObject.HasThing2);
DoThing3(myObject.HasThing3);
So each Do method makes the minimum number of tests, if any fail the it does nothing.
You can make it a bit cleverer if you want to break out of the sequence in few ways.
No idea whether it would work for you, but delegating the testing of the conditions is often enough of a new way of looking at things, that some simplifying factor might just appear as if by magic.
In my point of view there exists two main methods to eliminate nested conditions. The first one is used in more special cases when we have only one condition in each nested conditions like here:
function A(){
if (condition1){
if (condition2){
if (condition3){
// do something
}
}
}
}
we can just go out from the opposite condition with return:
function A(){
if (condition1 == false) return;
if (condition2 == false) return;
if (condition3 == false) return;
// do something
}
The second one is using a condition decomposition and can be treated as more universal than the first one. In the case when we have a condition structure like this, for example:
if (condition1)
{
// do this 1
}
else
{
if (condition2)
{
// do this 2
}
}
We can implement a variables for each particular condition like here:
bool Cond1 = condition1;
bool Cond2 = !condition1 && condition2;
if (Cond1) { //do this 1 }
if (Cond2) { //do this 2 }
If that really is the business logic then the syntax is OK. But I have never seen business logic that complex. Draw up a flow chart and see if that cannot be simplified.
if (condition)
{
// do this
}
else
{
if (condition)
{
// do this
}
}
can be replaced with
if (condition)
{
// do this
}
else if (condition)
{
// do this
}
But again step back and review the design. Need more than just an else if clean up.
I feel your pain.
My situation required writing many (>2000) functional tests that have been customer specified for a large, expensive piece of equipment. While most (>95%) of these tests are simple and have a straight forward pass/fail check dozens fall into the "multiple nested if this do that else do something different" at depths similar or worse than yours.
The solution I came up with was to host Windows Workflow within my test application.
All complex tests became Workflows that I run with the results reported back to my test app.
The customer was happy because they had the ability to:
Verify the test logic (hard for non programmers looking at deeply nested if/else C# - easy looking at a graphical flowchart)
Edit tests graphically
Add new tests
Hosting Windows Workflow (in .NET 4/4.5) is very easy - although it may take you a while to get your head around "communications" between the Workflows and your code - mostly because there are multiple ways to do it.
Good Luck
What is difference between these two examples:
if(firstchek)
{
if(second)
{
return here();
}
else
{
return here();
}
}
and this:
if(firstcheck)
{
if(second)
{
return here();
}
return here();
// else code without else
}
// code without else
// else code is here
return here();
This code:
if (someCondition)
{
foo();
return;
}
bar();
return;
is the same as this:
if (someCondition)
{
foo();
}
else
{
bar();
}
return;
The only difference is in readability. Sometimes one way is more readable, sometimes the other. See Refactoring: Replace Nested Conditional with Guard Clauses.
Nested conditionals:
double getPayAmount() {
double result;
if (_isDead) result = deadAmount();
else {
if (_isSeparated) result = separatedAmount();
else {
if (_isRetired) result = retiredAmount();
else result = normalPayAmount();
};
}
return result;
};
Guard clauses:
double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
};
Assuming there is no other code, there is no difference in terms of code paths and what gets executed.
The main difference, in general, is that when specifying an else clause, this will only run if the expression in the if evaluates to false. If you do not specify it, the code will always run.
Update:
This:
if(second)
{
return here();
}
else
{
return here();
}
And this:
if(second)
{
return here();
}
return here();
Would be the same as this:
return here();
Why? Because you are doing the same thing regardless of what second evaluates to, so the check is superfluous.
The two sets of code are semantically similar. That is to say they will perform the same at run time. However, Whether you should use one form or another depends on the situation. Your code should express your intent in addition to the required semantics.
If the intent of the code is to do one or the other then keep the else so your intent is explicit. E.g.
if (withdrawAmmount < accountBalance)
{
return Deduct();
}
else
{
return ArrangeCredit();
}
If however the intent is to do the first thing in a special case then feel free to omit the else. E.g.
if (parameter == null)
{
return NothingToDo();
}
return PerformActions();
For maintainability you should consider whether removing the return statements will change the behaviour and code on the basis that some idiot will do that (it could be me).
It should also be noted that with the else the code performs the same without the returns but without the returns omitting the else will cause the code to behave differently.
With the first code you are running something regardless if second is a defined value or not. It just depends on whether it is a defined value or not. If it is you run one bit of code. If it isn't then you run another. With the second example you will only run code if second is a defined value.
In the first case, the else part is only executed if the second variable is false.
In the second case, the part where the else is left out is always executed (given that firstcheck is true in both cases).
Your code has too many return statements that i feel as repetitive for example
if(firstchek)
{
if(second)
{
return here();
}
else
{
return here();
}
}
the above is equal to
if(firstchek)
{
return here();
}
because here() is the same function call. And the second example
if(firstcheck)
{
if(second)
{
return here();
}
return here();
// else code without else
}
// code without else
// else code is here
return here();
is equal to
if(firstcheck)
{
return here();
}
return here();
In the first example if there are some statement after the example and the top level if condition fails then the statements following it will be executed example
if(firstchek)
{
if(second)
{
return here();
}
else
{
return here();
}
}
CallMyCellNo();
CallMyCellNo() will be called if the toplevel if condition fails.
In the second example you have return here() after the toplevel if statement so regardless of the if condition's return value the function execution will terminate.