07 December 2011

C# Lesson 7 : Branching with the if Decision Statement and the Conditional Operator

Branching allows us to add logic to our applications. This lesson introduces the ‘if Decision’ statement (in its various forms), along with the conditional operator. We also discuss how to refactor our code to make it more compact and less likely to produce errors, by eliminating duplicate code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Decisions
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Please type something and press the Enter key.");
            //string userValue;
            //userValue = Console.ReadLine();
            //Console.WriteLine("You typed: " + userValue);


            Console.WriteLine("Would you prefer what is behind door number 1, 2, or 3?");
            string userValue = Console.ReadLine();

            //string message = "";

            //if (userValue == "1")
            //{
            //    message = "You won a new car!";
            //}
            //else if (userValue == "2")
            //    message = "You won a new boat!";
            //else if (userValue == "3")
            //    message = "You won a new cat!";
            //else
            //    message = "Sorry, we didn't understand.  You lose!";

            //Console.WriteLine(message);


            string message = (userValue == "1") ? "boat" : "strand of lint";
            Console.WriteLine("You won a {0}", message);

            Console.ReadLine();
        }
    }
}
Source : MS Virtual Academy

No comments: