ideas | discover | explore

Sunday, September 18, 2011

C# 6 - – What If? Or, Else If....?


1. Create a new console project.
2. Edit the Program.cs file as shown below.



        static void Main(string[] args)
        {
            Console.WriteLine("What is your most favorite sweet stuff?");
            Console.WriteLine("[1]Chocolate");
            Console.WriteLine("[2]Candy");
            Console.WriteLine("[3]Lollipop");
            Console.WriteLine("[4]Sugar");
            Console.WriteLine("[5]Honey");
            Console.WriteLine("[6]Cake");
            Console.Write("Enter your choice: ");
            string choice = Console.ReadLine();
 
            if (choice=="1")
            {
                Console.WriteLine("Chocolate, chocolate, chocolate!");
            }
            else if (choice == "2")
            {
                Console.WriteLine("Candy, candy, candy!");
            }
            else if (choice == "3")
            {
                Console.WriteLine("Lollipop, lollipop, lollipop!");
            }
            else if (choice == "4")
            {
                Console.WriteLine("Sugar, sugar, sugar!");
            }
            else if (choice == "5")
            {
                Console.WriteLine("Honey, honey, honey!");
            }
            else if (choice == "6")
            {
                Console.WriteLine("Cake, cake, cake!");
            }
            else
            {
                Console.WriteLine("Hmmm, I don't know what you're favorite is.");
            }
 
            Console.WriteLine("Press any key to continue.....");
            Console.ReadLine();
        }

3.       Press F5 to run and see the results.

The if-else-if statement is used to add multiple condition to a piece of code. Sort of like a chained if-else statement Its syntax is: 



if(<condition>)
     //code
else if(<condition>)
     // any other code
else
     //this code will execute if there are no matching conditions


Condition – could be anything that would result in a true or false. If only runs the code inside its braces when the condition is true. If the condition fails or evaluates to false the code under the else will get executed.


No comments: