In this post, we will try to explore the if, if-elseif-else, if-else statement of C# language by focusing on its syntax and showing more examples in the latter part. Practically, these statements are used for logical or conditional testing within a block of code. To elaborate further, if you have to check for a certain value and evaluate it to either true or false and then from the result of the evaluation, you can do some actions. Expression, in technical terms, is also known as “Boolean expression” which can be evaluated to true or false.
About the examples below, you might notice the usage of WriteLine-method directly, it is because of the using static directive.
- using static System.Console;
Now, let's get started with the syntaxes of the if, if-else, if-elseif-else statements. Please, see the syntaxes below.
If-statement syntax
- var booleanExpression = true;
- if (booleanExpression)
- {
- //write your statement here
- }
- if(booleanExpression)
- {
- //write your statement here
- }
- else
- {
- //write your statement here
- }
If-elseif-else statement syntax
- if(booleanExpression)
- {
- //write your statement here
- }
- else if (booleanExpression)
- {
- //write your statement here
- }
- else
- {
- //write your statement here
- }
Now that we have a good grasp of the basic syntax. Let’s raise the bar a bit by showing examples based on the syntax shown above. Let’s get started.
If-statement syntax
- var dayOfWeek = DateTime.Now.DayOfWeek; //|Lets check if the day of week is Friday|
- string statement = "Thank God Its Friday!";
- if (dayOfWeek == DayOfWeek.Friday) //|When it is Friday let's celebrate yehey!
- {
- WriteLine(statement);
- }
If-else syntax
- const int MY_BIRTH_YEAR = 1982;//|Year I was born|
- int birthYear = DateTime.Now.AddYears(-37).Year;
- bool booleanExpression = (birthYear == MY_BIRTH_YEAR);
- string statement = "";
- if (booleanExpression) //| If the 'booleanExpression' is true this will be executed.|
- {
- statement = $"Yes I was born in the year {MY_BIRTH_YEAR}";
- WriteLine(statement);
- }
- else //| If the 'booleanExpression' is equivalent to false this will be executed.|
- {
- statement = $"Sorry I was born in the year {MY_BIRTH_YEAR}";
- WriteLine(statement);
- }
If-elseif-else statement syntax
- int operatingSystemVersion = Environment.OSVersion.Version.Major;
- if (operatingSystemVersion == 10)
- {
- WriteLine("You are probably on Windows 10|2016|2019");
- }
- else if (operatingSystemVersion == 6)
- {
- WriteLine("You are probably on Windows 8|7|Vista|2008");
- }
- else if (operatingSystemVersion == 5)
- {
- WriteLine("You are probably on Windows XP|2000|2003");
- }
- else
- {
- WriteLine("Your computer is a dinosaur");
- }


Join the conversation! Your thoughts help the community grow.