Lesson 12 - The Conditional Ternary Operator

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article

Get GitHub Code

In this lesson, we'll cover a handy shortcut for writing an if() and else() statement called the ternary operator. This shortcut does the same kind of flow control as an if() statement, branching off and executing one of two possible conditions. If you need to evaluate more than two possible conditions, stick with using the if(), else if(), else() set of conditional statements. However, the ternary operator is a great shortcut for simple if/else conditional logic.

Step 1: Create a New Project

As always, the code associated with this lesson is available in the provided folder under CS-ASP_012. In the Before folder, open up the Project called CS-ASP_012 and skip ahead to Step 2. Otherwise, set up the Project manually as follows:

Create a new ASP.NET project called “CS-ASP_012” and set it up with the following Server Controls:


The programmatic IDs for these Controls are:

  1. firstTextBox

  2. secondTextBox

  3. oldCheckBox

  4. okButton

  5. resultLabel

Step 2: Create a Statement using the Ternary (?) Operator

Now let’s write a statement in the okButton_Click event to evaluate whether or not the two TextBoxes are equal, then tell the user using the resultLabel. We previously learned to do this using an if() and else() statement. However, using the ternary operator, we can write this evaluation all in one line of code. and then run the application:




Step 3: Breaking Down the Ternary Operator

The ternary statement may look odd at first, but when you learn how to interpret it, you will find it’s no different than the conditional statements we’ve been writing thus far. Here is how you can read this statement:


  1. If…

  2. firstTextBox.Text is equivalent to secondTextBox.Text

  3. then, resultLabel.Text equals

  4. “Yes”

  5. else…

  6. “No”

The question mark (1) is the same as saying "if", then what is inside the parentheses (2) is the conditional check. Is firstTextBox.Text equivalent to secondTextBox.Text? (3) resultLabel's Text Property will be set depending on the result of the evaluation. If true, then set the Text equal to "Yes" (4). The colon (5) denotes the else statement, and the following string (6) is the value to be assigned if the evaluation is false.

Now, let’s create a ternary statement for the CheckBox control.


Tip: Your eyes are not playing tricks on you! Recall that whitespace is ignored by the compiler, leaving it up to you how to style code to make it easier to read. In this case, we chose to split the ternary statement on multiple lines simply because it was running off the screen. But make no mistake, this is still just one statement with a single semi-colon on the end.

Remember, the evaluation for oldCheckBox.Checked implies a Boolean value, so we do not have to write out the full expression of oldCheckBox.Checked == “true”. Running the application will produce the same branching nature as we have come to expect:



Step 4: A “game-like” Example of the Ternary in Action

Combining several things we’ve learned so far, let’s write out a ternary statement that demonstrates how we might go about using it for a game-like situation. In this scenario, different score values may be awarded depending on if an equivalence has been evaluated as true or false.




The beauty of the ternary operator is its simplicity; but it comes with a cost. You cannot have a complex, multi-conditional evaluation and use a ternary operator. However, for simple evaluations, it's much shorter and simpler, as long as you remember the proper syntax for it. Good job in this lesson, keep it up!

Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Please login or register to add a comment