System ProgrammingLearn about Ternary Operator & switch Statement in C# programming

Learn about Ternary Operator & switch Statement in C# programming

In the previous article, we started to discuss the topic of conditionals and decision making in C#. We have learned the if…else statement and how we can use it to control the program flow. In the same context, C# programming offers two short alternatives that could be very useful when called inside a large block of code. The two alternatives are the ternary operator and the switch statement. Learning how to use both tools will be the subject of this article. A short article it will be, but a useful one. So, bear with us.

The Ternary operator

Consider the following simple if … else statement:

string message;
int result = 60;
if (result > 50) 
{
	message = "Passed";
}
else 
{
	 message = "Failed";
}
Console.Wri¬teLine(message);

Using the ternary operator, the above code can be rewritten as follows:

string message;
int result = 60;
message = result > 50 ? "Passed" : "Failed";
Console.WriteLine(message);

As you could see, eight lines of code have been squeezed into just one statement that will do the same job exactly: assign one of two strings to a message based on the value of the result variable. You have just written your first ternary operator. Have you seen how short and simple it is?!

The switch statement

The switch statement enables us to test a single variable against a number of values. It is different from if statement in that you can not do logical operations inside it. Imagine you have some sort of gauge that has three levels of report: red for alert, orange for warning, and green for normal. You want to print a message to the user depending on the current color of the gauge. You’d do something like the following:
string color=”red”;

switch(color)
{
	case "red":
		Console.WriteLine("Alert");
		break;
	case "orange":
		Console.WriteLine("Warning");
		break;
	default:
		Console.WriteLine("All clear");
}

If you execute the above code, you will find “Alert” printed to the screen. Notice that we did not put a switch statement for the “green” color, as this is the only left option.
The switch statement takes a variable (color) and checks its value against a set of possible values, and then prints the result if one of them matches, or print “All clear” if no matches were found. You need to follow each statement code with the break statement that instructs the program to exit the block once the match is found.
It is worth mentioning that switch statements could be also used to test for two conditions at the same time. For example:

string color="red";
switch(color)
{
	case "red":
		Console.WriteLine("Alert");
		break;
	case "orange":
	case "yellow":
		Console.WriteLine("Warning");
		break;
	default:
		Console.WriteLine("All clear");
}

Here I am testing for two values at the same time: orange and yellow, and I want to execute the same code if any of them is a match.

Learn Cloud Computing from Scratch for Beginners

Rules for Using switch Statement

Using the switch statement has some restrictions. The following points list these restrictions:

• The switch statement must be used with constant (literal) values. i.e. The expressions specified in the individual case blocks must be constants like 15, “Sunday”, etc.

• The switch statement can be used to test a variable against values that belong to one of the basic data types (like strings and integers). Floating-point numbers can not be tested using switch statement.

• The case constants must be unique.
• switch statements can not be used to do logical operations. That is, you can not say:

switch (grade) 
{
	case >= 50:
	# some code

This code is illegal and will not work; the switch statement works with discrete values comparison using == (the case part) and != (the default part).

Summary
In this article, we have continued our talk on Decision Making.
• The ternary operator is a short alternative for an if…else structure with single statement in the body of both parts if and else.
• The switch statement is useful when testing a single variable against a list of values for equality.
• switch statement could be used only to test constant values of the type string or integer.
That is it for Decision Making. The next article will talk about Loops. A very important and interesting topic indeed. So, don’t miss it. See you there!!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -