c# curly brackets | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

c# curly brackets

Hello, I don't really understand the difference in the usage of the curly brackets (or the lack of) in the two following examples: 1. int x = 8; int y = 3; if (x > y) { Console.WriteLine("x is greater than y"); } 2. int age = 42; string msg; if(age >= 18) msg = "Welcome"; else msg = "Sorry"; Console.WriteLine(msg); When are the curly brackets actually necessary? Thanks! :)

25th Apr 2018, 9:10 AM
Sandra
Sandra - avatar
5 Answers
+ 4
Sandra, If you want to execute multiple lines after if or else condition you need to make a block with the help of brackets. Like if(age>20) { Print("Line 1"); Print("Line 2") Print("Line 3") Or other conditions etc } If you want to execute only one line after if or else condition you didn't need to make block with brackets Like if(age > 20) Print("Line 1") But if you make block only for one line there is no effect, so in my opinion make practice to use brackets either you have one line or multiple lines to execute. Thanks - Salman
25th Apr 2018, 9:24 AM
Salman Mushtaq
Salman Mushtaq - avatar
+ 2
Curly brackets are necessary when you need to execute multiple statements in a condition. If it is just one, you can omit them. For example: int y = 10; int x; if (y > 10) x = y; else x= y + 10; // As the statement you to need to // execute in the if and else is just one, // you can omit the curly braces. if (y > 10) { x = y; Console.Write(x); } else x = y + 10; // In this case, as you have multiple // statements to execute in the if // clause, you must use the curly // braces. if (y > 10) x = y; Console.Write(x); // Here, Console.Write(x); will run in // any case, as it is not bound to // the if clause if (y > 10) x = y; Console.Write(x); else x = y + 10; // As you may imagine, this code // produces an error, as the else // statement can't find a previous if // statement. // This is because the Console.Write(x); // isn't being executed in the if, and so it // breaks the boundary between if and // else // You can omit the curly braces in // almost any conditional instructions for (int i = 0; i < 10; i++) Console.WriteLine(i); while (true) Console.Read(); do Console.Read(); while (true); foreach (int num in myNumArr) Console.WriteLine(num); // And so on Hope I was clear enough
25th Apr 2018, 9:33 AM
Mante
Mante - avatar
+ 1
thank you so much! I really appreciate your help and examples!
25th Apr 2018, 9:23 PM
Sandra
Sandra - avatar
0
You're welcome!
26th Apr 2018, 4:33 AM
Mante
Mante - avatar
0
Too bad the “AI friend” doesn’t tell you.
19th Apr 2024, 12:40 PM
Alexander Rose
Alexander Rose - avatar