Using Decision Statements in C#
Using the ?: Operator or ternary operator and If Else
C# performs the statements in a program in a sequential
manner. However, you frequently need to specify that alternative statements
should run depending on the value of an expression or a Boolean condition. To
achieve this ,C# provides conditional decision statements. Explain how to use the if
else statement.
1.
Using If Else
2.
Using ?: operator.
3.
Using
switch
statement
If
else
1.
If
([Condition]) //Code to Execute
2
.If ([Condition])
{
//If condition is true
//Code to Execute
}
3.
.If ([Condition1] && [Condition2])
{
//If condition is true
//Code to Execute
}
4.
.If ([Condition1] || [Condition2])
{
//If condition is true
//Code to Execute
}
if statements are very useful when you want to execute a code
statement based on a condition. The basic syntax for a one-way if statement is
shown in the following code example.
if ([condition]) [code to execute]
if the expression [condition] evaluates to a Boolean true
value, [codeto execute] is executed. Notice that the condition must be enclosed
in parentheses.You can execute more than one code statement. To do this, you
delimit the code to run by using braces. This extends the syntax as the
following code example shows.
if ([condition])
{
[code to execute if condition is true]
}
If(a>50)
{
C=a+b;
}
If Else statement
Provides additional code block to execute if [Condition] is
evaluates to boolean false
If([Condition])
{
//Execute code
}
Else
{
//Else code to execute
}
Using the ?:
Operator or ternary operator
As an alternative to using the if else statements, in some
simple cases, you can use
the “?: “ ternary operator.The basic syntax to use the ?: operator
is shown in the following code example.
Type result = [condition] ? [true expression] : [false
expression]
If the expression [condition] evaluates to true, [true
expression] is executed, but if the [condition] evaluates to false, [false
expression] is executed.The following code example shows an example of using
the ?: operator to check the value of a string, and then return a response.
string penColor = "green";
string response = (penColor == "red") ? "You
have a red pen" :"You do not have a red pen";
Nice post very helpful
ReplyDeletedbakings