Knowledge Transfer

Wednesday, January 7, 2009

C# Ternary Operator

Hi DotNetGems,
First we discuss about the If..Else . I think Every one know about If..else and Nested If Else statements so same like that we use the Ternary Operators.the symbole is like this "?:".

If..else example

using System;
class Program
{
static void Main(string[] args)
{
int age = 31;
if (age > 75)
Console.WriteLine("Have a nice retirement");
else
Console.WriteLine("You are still young");
Console.Read();
}
}

Now The Ternary Operator

The ternary operator looks like this: "?:"
Ternary operator has one condition expression and can return one of possible two values. Lets take a look at an example:

using System;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
int a = 1;
string b = (a < 2) ? "true" : "false";
Console.WriteLine(b);
Console.Read();
}
}
}



Happy coding
Uday.Adidham

Labels: , ,

1 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home