Conditional Statements

If, For, Switch loops defined

If Loop:

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

Syntax

The syntax of an if...else statement in C# is −

if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
} else {
   /* statement(s) will execute if the boolean expression is false */
}

If the boolean expression evaluates to true, then the if block of code is executed, otherwise else block of code is executed.

= used for assignments like int x = 5 == equality (like -eq in posh) != not equal to ( here ! Is also called as bang, so bang equal or not equal) && is read as and. So both conditions should be true. || is read as "OR"

var name1 = "John";
int age = 22;
if (age > 20 && name1 != "John")
{
Console.WriteLine($"{name1} can vote");
}
else
{
Console.WriteLine($"{name1} cannot vote");
}

You can also use else if like else if (age > 33 && name1 == "John") { } If you have only one condition, then you don’t have to use { } in a if statement, like if (val > 6 && name == "John" ) you can specify next command directly without {}. Specify like this: if (val > 6 && name == "John" ) Console.writeline($"John is the name") Don’t specify { } in if loop. But this is poor programming practice. Always use { }

For Loop:

it has 3 parts: Initialization - For(int i =0 Test - for(int i=0; i< 10 Increment - for (int i=0;i<10;i++)

for (int i=1;i<10;i++)
{
Console.WriteLine(i.ToString());
}

While loop and Do while loops:

While: While some condition is true, run the statement. Do while: Run the statement and chek if condition is true. This will run the statement minimum once.

int k = 0;
while (k < 100)
{
Console.WriteLine($"value of k is {k}");
k++;
}

Do while example:

int k = 0;
do
{
Console.WriteLine($"value of k is {k}");
k++;
}while (K < 0); // here it will print k value once and then stops as k = 0, and we are checking if k < 0

constants: using constants we assign values to variables, but it doesnt change. ex: const double pi = 3.14

Enumerated constants: Enums are known as named constants. If we have some constants related to each other then we can use an enum to group all the constants. Declare enum in class program block and call those values in main block in the script.

Use enums when you want to define a range of values that something can be. Colour is an obvious example like:

public enum Colour
{
    White,
    Red,
    Blue
}

Or maybe a set of possible things like: (Example I stole from here as I'm lazy)

[FlagsAttribute]
enum DistributedChannel
{
  None = 0,
  Transacted = 1,
  Queued = 2,
  Encrypted = 4,
  Persisted = 16,
  FaultTolerant = Transacted | Queued | Persisted
}

Constants should be for a single value, like PI. There isn't a range of PI values, there is just PI.

Ex:

namespace ifdemo
{
class Program
{
enum Kidsages
{
cricket = 10,
volleyball = 20,
nap=5
}
static void Main(string[] args)
{
const int age = 15;
if (age <= (int)Kidsages.cricket)
{
Console.WriteLine("can play cricket");
}
else if (age < (int)Kidsages.volleyball && age >(int)Kidsages.cricket)
{
Console.WriteLine("can play volleyball");
}
}
}

Switch Statements:

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case

class Program
{
enum list
{
movies,
songs,
audio
}
static void Main(string[] args)
{
list bestmovie = list.movies;
switch (bestmovie)
{
case list.movies:
Console.WriteLine("You chose movies");
break;
case list.songs:
Console.WriteLine("you chose songs");
break;
case list.audio:
Console.WriteLine("you chose audio");
break;
default:
Console.WriteLine("Please try again");
break;
}
}
}

In switch we have a variable in switch statement, and we compare that variable with different conditions. If any of those conditions meet, break the loop.

Switch(name)
{
Case name.john:
Statement
Break;
Case name.david:
Statement
Break;
Default:
Statement
Break;
}

Ex:

public enum Season
        {
            autumn,
            sprint,
            summer,
            someotherseason
        }
static void Main(string[] args)
         {
             var weather = Season.someotherseason;
             switch (weather)
             {
                 case Season.autumn:
                     Console.WriteLine("season is autumn");
                     break;
                 case Season.sprint:
                     Console.WriteLine("Season is sprint");
                     break;
                 case Season.summer:
                     Console.WriteLine("Season is summmer");
                     break;
                 default:
                     Console.WriteLine("It is summer season");
                     break;
             }
         }

If you expect same result for two case statements, you can combine them as:

static void Main(string[] args)
         {
             var weather = Season.someotherseason;
             switch (weather)
             {
                 case Season.autumn:
                 case Season.sprint:
                     Console.WriteLine("Season is sprint");
                     break;
                 case Season.summer:
                     Console.WriteLine("Season is summmer");
                     break;
                 default:
                     Console.WriteLine("It is summer season");
                     break;
             }
         }

IF you see season.autumn doesnt have an output statement. It uses same output as season.summer.

Simple switch case example:

int i = 3; 
switch (i) 
{ 
case 1: 
Console.WriteLine("One"); 
break; 
case 2: 
Console.WriteLine("Two"); 
break; 
}

Boolean operator:

bool result = false;
             int variable=100;
             //if (result == 10)
             //{
             //    result++;
             //    Console.WriteLine(result);
             //}
             //else if (result != 10)
             //{
             //result += 100;
             //Console.WriteLine(result);
             int finalresult = (result) ?  variable ++: variable += 100;
             Console.WriteLine(variable);

Normally we write code, as shown in the commented section in above code. But only for boolean operators we can write code as:

Datatype variable = (boolean condition) ? Statement1 : statement2

We check for boolean condition, I above example, it checks, if result is true. (result) means, checking the value of result. ? means if it is true. If it is true increase value of variable. For else we use full colon : . If result is true, add 1 to the value of variable. If not, add 100 to value of variable.

so, all above commented code can be written in single line as:

int finalresult = (result) ? variable ++: variable += 100;

Break and Continue:

Break statement is used to terminate the current loop iteration or terminate the switch statement in which it appears. If you have break command in a loop, when the condition is true, it will terminate the script and stops execution immediately.

static void Main(string[] args)
        {
            string[] kk = new string[3] { "John", "David","Peter" };
            foreach (string vv in kk)
            {
                if (vv == "David")
                {
                    break;
                }
                else
                {
                    Console.WriteLine("name is {0}",vv);
                }
            }

        }

Here, output would be "name is John" and stops there because after it prints "name is john" and goes for second loop, when it checks for name David, we used break command. It breaks the loop and comes out. As there is no other code in the script, it will stop the whole script. If you have some other code like for loop, or if loop after this foreach loop, it will continue evaluating that code.

Continue command will skip the execution of loop only once where the condition is met.

static void Main(string[] args)
        {
            string[] kk = new string[3] { "John", "David","Peter" };
            foreach (string vv in kk)
            {
                if (vv == "David")
                {
                    continue;
                }
                else
                {
                    Console.WriteLine("name is {0}",vv);
                }
            }

        }

Here output will contain "name is john", "name is peter". When it checks for David, it skips the execution of that loop only for one iteration.

Last updated