Use Ternary Operator In C# Language

Introduction

In c# language, ternary operator (?) use to check a conduction, so other name of ternary operator is conditional operator, which work as a if statement. This operator compares two values. It produces a third value that depends on the result of the comparison. At compile-time, the C# compiler translates the ternary expression into branch statements such as brtrue.

Example:

using System;

namespace Ternary_____operator_in_c_sharp

{

    class login     //create class

    {

 

        public string check(string name, int pass) //Create function

        {

            //Use ternary operator ?

            //condition true then reply "Welcome Arvind"

            //condition falls then reply "Invalid Login or Password"

            return name == "arvind" && pass==123 ? "Welcome Arvind":"Invalid Login or Password";

            

        }

   

    }

    class Program

    {

        static void Main(string[] args)

        {

            login log = new login();  //create object of class login

 

             //call to check function with values and then show result

            Console.WriteLine(log.check("arvind",123));

 

            Console.ReadLine();

        }

    }

}


Output:


output.jpg


Note: If you pass another int value which do not match in pass parameter variable, then show second output message is "Invalid Login or Password".

Ebook Download
View all
Learn
View all