This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

?: operator - the ternary conditional operator

  • 11 contributors

The conditional operator ?: , also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false , as the following example shows:

As the preceding example shows, the syntax for the conditional operator is as follows:

The condition expression must evaluate to true or false . If condition evaluates to true , the consequent expression is evaluated, and its result becomes the result of the operation. If condition evaluates to false , the alternative expression is evaluated, and its result becomes the result of the operation. Only consequent or alternative is evaluated. Conditional expressions are target-typed. That is, if a target type of a conditional expression is known, the types of consequent and alternative must be implicitly convertible to the target type, as the following example shows:

If a target type of a conditional expression is unknown (for example, when you use the var keyword) or the type of consequent and alternative must be the same or there must be an implicit conversion from one type to the other:

The conditional operator is right-associative, that is, an expression of the form

is evaluated as

You can use the following mnemonic device to remember how the conditional operator is evaluated:

Conditional ref expression

A conditional ref expression conditionally returns a variable reference, as the following example shows:

You can ref assign the result of a conditional ref expression, use it as a reference return or pass it as a ref , out , in , or ref readonly method parameter . You can also assign to the result of a conditional ref expression, as the preceding example shows.

The syntax for a conditional ref expression is as follows:

Like the conditional operator, a conditional ref expression evaluates only one of the two expressions: either consequent or alternative .

In a conditional ref expression, the type of consequent and alternative must be the same. Conditional ref expressions aren't target-typed.

Conditional operator and an if statement

Use of the conditional operator instead of an if statement might result in more concise code in cases when you need conditionally to compute a value. The following example demonstrates two ways to classify an integer as negative or nonnegative:

Operator overloadability

A user-defined type can't overload the conditional operator.

C# language specification

For more information, see the Conditional operator section of the C# language specification .

Specifications for newer features are:

  • Target-typed conditional expression
  • Simplify conditional expression (style rule IDE0075)
  • C# operators and expressions
  • if statement
  • ?. and ?[] operators
  • ?? and ??= operators
  • ref keyword

Additional resources

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, certification courses.

Created with over a decade of experience and thousands of feedback.

Introduction

  • Getting Started with C#
  • Your First C# Program
  • C# Comments
  • C# Variables and (Primitive) Data Types

C# Operators

  • C# Basic Input and Output
  • C# Expressions, Statements and Blocks

Flow Control

C# if, if...else, if...else if and Nested if Statement

C# ternary (? :) Operator

  • C# for loop
  • C# while and do...while loop
  • Nested Loops in C#: for, while, do-while
  • C# break Statement
  • C# continue Statement

C# switch Statement

  • C# Multidimensional Array
  • C# Jagged Array
  • C# foreach loop
  • C# Class and Object
  • C# Access Modifiers
  • C# Variable Scope
  • C# Constructor
  • C# this Keyword
  • C# Destructor
  • C# static Keyword
  • C# Inheritance
  • C# abstract class and method
  • C# Nested Class
  • C# Partial Class and Partial Method
  • C# sealed class and method
  • C# interface
  • C# Polymorphism
  • C# Method Overloading
  • C# Constructor Overloading

Exception Handling

  • C# Exception and Its Types
  • C# Exception Handling
  • C# Collections
  • C# ArrayList
  • C# SortedList
  • C# Hashtable
  • C# Dictionary
  • C# Recursion
  • C# Lambda Expression
  • C# Anonymous Types
  • C# Generics
  • C# Iterators
  • C# Delegates
  • C# Indexers
  • C# Regular Expressions

Additional Topics

  • C# Keywords and Identifiers
  • C# Type Conversion

C# Operator Precedence and Associativity

  • C# Bitwise and Bit Shift Operators
  • C# using Directive
  • C# Preprocessor Directives
  • Namespaces in C# Programming
  • C# Nullable Types
  • C# yield keyword
  • C# Reflection

C# Tutorials

  • C# Expressions, Statements and Blocks (With Examples)

Ternary operator are a substitute for if...else statement. So before you move any further in this tutorial, go through C# if...else statement (if you haven't).

The syntax of ternary operator is:

The ternary operator works as follows:

  • If the expression stated by Condition is true , the result of Expression1 is returned by the ternary operator.
  • If it is false , the result of Expression2 is returned.

For example, we can replace the following code

Why is it called ternary operator?

This operator takes 3 operand , hence called ternary operator.

Example 1: C# Ternary Operator

When we run the program, the output will be:

In the above program, 2 is assigned to a variable number . Then, the ternary operator is used to check if number is even or not.

Since, 2 is even, the expression ( number % 2 == 0 ) returns true . We can also use ternary operator to return numbers, strings and characters.

Instead of storing the return value in variable isEven , we can directly print the value returned by ternary operator as,

When to use ternary operator?

Ternary operator can be used to replace multi lines of code with a single line. However, we shouldn't overuse it.

For example, we can replace the following if..else if code

with a single line of code

As we can see, the use of ternary operator may decrease the length of code but it makes us difficult to understand the logic of the code.

Hence, it's better to only use ternary operator to replace simple if else statements.

Table of Contents

  • Ternary Operator Introduction
  • Example: C# Ternary operator
  • When to use it?

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

C# Tutorial

C# Ternary Operator: How to Use it Effectively?

C# Ternary Operator

What is the C# Ternary Operator?

Can’t wait to simplify your coding life? Are you wondering what’s the secret to writing faster C# conditional logic? Alright, keep reading as we delve into all the nitty-gritty details of the C# Ternary Operator.

Definition and Usefulness of C# Ternary Operator

The C# Ternary Operator is quite emerging as a powerful, compact substitute for lengthy if-else statements. Comprising only three operands, it speeds up your coding process like a charm. Its syntax condition ? expr1 : expr2 means: if condition is true, expr1 is executed; otherwise, it’s expr2 .

In other words, grab a cup of coffee and bid subtitles goodbye as we save lots of space on your screen, minus those endless lines of braces and parentheses!

Imagine the beauty of this. With just a single line of code, we’ve executed an if-else statement! Fascinating, isn’t it?

Exploring The Syntax of C# Ternary Operator

Craving more? Here’s a closer look at the syntax of the C# Ternary Operator. You’d be astonished at the power this little operator holds.

How Does the C# Ternary Operator Work

Surprisingly, the ternary operator is an operator in C# that takes three operands (surprise)! It’s like the role of an efficient traffic policeman, controlling what gets prioritized depending on a particular condition (appointments, if you will).

Above, our friendly ternary cop decides if it’s morning or afternoon based on the current time. Efficiency and simplicity, friends!

Dive Deep into the Practical Examples

Ready for the adventure? Here we go. Sit back, grab your cup of coffee, and enjoy the beauty of practical examples with the C# ternary operator!

Simple C# Ternary Operator Example

Check out this cool example that displays how the C# ternary operator can be used to decide a simple status message:

Whoa! With a flick of a finger, you’ve got the system status. Pretty awesome, right?

Advanced C# Ternary Operator Multiple Statements Example

You might be thinking, “Can we use more than one statement with a ternary operator?” Well, here’s an exciting twist! The C# ternary operator does also support multiple statements. However, the catch is, you’ll need to use a workaround using Lambda methods. Let’s take a peek:

Here, we’re invoking immediate functions depending on our condition. Interesting, huh? Just goes to show, there’s always a way!

Streamlining Code with C# Ternary Operator

Lost in a maze of if-else? Fear not! As we’re about to swing the door wide open with the magic of the C# ternary operator. Let’s dig deeper!

Talking about C# If Ternary Operator

So, you’re probably wondering how you can achieve a more succinct conditional without those nested braces. Only if there were a shorter way… oh, wait! There is, and it’s called the C# If ternary operator.

So, instead of writing several lines for if-else, you’ve simply used a one-line ternary operator. How’s that for efficiency?

Convert If Else to Ternary Operator C#

Imagine a world free from lengthy and messy if-else codes? That’s not too difficult. You’re about to witness the magic of converting lengthy if-else to sleek one-liner ternary operators in C#.

The magic is real! In a single line, we’ve determined the state of water depending on the temperature.

Ternary Operator Assignments

How about assigning values with the ternary operator? Don’t worry; C# has got this covered as well!

Understanding C# Ternary Operator Without Assignment

Normally, you would see a ternary operator along with an assignment. But what if you wanted to certainly perform actions without assigning a value to any variable? Fret not, the C# ternary operator is flexible enough to allow that!

See? No assignments, yet actions were performed based on our condition!

Working with Null and Else in C# Ternary Operator

Do you wonder how to efficiently bypass Null and Else while working with ternary operators? Well, this is just the right place for you.

C# Ternary Operator Null Use Cases

What happens when you assign null values using a ternary operator? Let’s find out!

This code can help in checks to prevent NullReference exceptions, making your app more robust. Impressive, no?

Ways to Implement C# Ternary Operator Without Else

Ternary without Else, you say? Absolutely! You can use a ternary operator without explicitly specifying the Else part, and C# will automatically insert a default else clause returning the default value of the data type.

Super amazing, right? Only in C#, folks!

How to Work with Multiple Ternary Operator C#?

Handling multiple conditions can sometimes feel like juggling flaming torches. It’s hot stuff, and mistakes can be messy! However, the C# ternary operator is here to help. With its syntax, we can elegantly handle complex condition checking, turning flaming torch juggling into a gentle cascade of lit matchsticks.

Perfectly timed to catch each one safely, have a look at this simple arrangement:

In this snippet, we’re checking the age categories. But we can extend this to incorporate more complex logic, perhaps involving database queries or calculations.

Let’s consider a real-life application: grading students based on score ranges.

In this example, the student’s grade is being determined based on their score. If the score is above 85, the student earns an A. Otherwise, the code checks if it’s above 75 for a B, then above 65 for a C, and so on. If all these conditions are false, it implies the student has failed, hence the F grade is assigned.

It’s kind of like going through a checklist: checking conditions in order, from top to bottom, until one condition fits. This sequence of checks by the ternary operator makes multiple condition handling a breeze.

Let’s take it up another notch! Now, how about assigning priorities to tasks based on both their importance and urgency?

In this scenario, if both importance and urgency score above 7, the task has a high priority. If either of them scores above 5, it is of medium priority. If neither condition is met, the task is low priority.

Using Ternary Operator to Increase the Performance and Readability of Your Code

By now, you’d probably be nodding in agreement that the Ternary Operator in C# is a compact, efficient and sensible alternative to traditional conditional statements like if-else.

Above all, always remember, just like their favorite superhero, every developer has a superpower: the ability to simplify and enhance the reader’s understanding. Apply these techniques, and bring your code to life! Happy Coding!

Sign up For Our Newsletter

Weekly .NET Capsules: Short reads for busy devs.

Related Posts

Comprehensive Guide to Metadata and Attributes in C# 12

Comprehensive Guide to Metadata and Attributes in C# 12

ByteHide

Abstraction vs. Encapsulation in C#

Store Temporary Information

How to Store Temporary Information in Table-Like Format in C#

Leave a reply cancel reply.

Save my name, email, and website in this browser for the next time I comment.

ByteHide Solutions S.L.

  • Obfuscation
  • Secrets Management
  • Threat Monitoring
  • Request a Demo
  • Documentation
  • Help Center
  • Terms of Service
  • Privacy Policy
  • Cookies Policy

© 2024 ByteHide.

  • Cybersecurity Glossary

ByteHide utilizes cookies to enhance your browsing experience. For more detailed information about our use of cookies, please review our Cookie Policy

C# Tutorial

C# examples, c# short hand if...else, short hand if...else (ternary operator).

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:

Instead of writing:

Try it Yourself »

You can simply write:

C# Exercises

Test yourself with exercises.

Print "Hello World" if x is greater than y .

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

assignment in ternary operator c#

C# - Ternary Operator ?:

C# includes a decision-making operator ?: which is called the conditional operator or ternary operator. It is the short form of the if else conditions.

The ternary operator starts with a boolean condition. If this condition evaluates to true then it will execute the first statement after ? , otherwise the second statement after : will be executed.

The following example demonstrates the ternary operator.

Above, a conditional expression x > y returns true, so the first statement after ? will be execute.

The following executes the second statement.

Thus, a ternary operator is short form of if else statement. The above example can be re-write using if else condition, as shown below.

Nested Ternary Operator

Nested ternary operators are possible by including a conditional expression as a second statement.

The ternary operator is right-associative. The expression a ? b : c ? d : e is evaluated as a ? b : (c ? d : e) , not as (a ? b : c) ? d : e .

  • Difference between Array and ArrayList
  • Difference between Hashtable and Dictionary
  • How to write file using StreamWriter in C#?
  • How to sort the generic SortedList in the descending order?
  • Difference between delegates and events in C#
  • How to read file using StreamReader in C#?
  • How to calculate the code execution time in C#?
  • Design Principle vs Design Pattern
  • How to convert string to int in C#?
  • Boxing and Unboxing in C#
  • More C# articles

assignment in ternary operator c#

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

  • C# Questions & Answers
  • C# Skill Test
  • C# Latest Articles

C# Ternary Operator: Simplify Conditional Expressions

The C# ternary operator, also known as the conditional operator, is a valuable tool for programmers to write concise and efficient code. This operator evaluates a Boolean expression and returns one of two specified values based on whether the expression is true or false. It serves as a compact alternative to the traditional “if-else” statements, allowing developers to streamline their code and improve readability.

In C# language, the ternary operator is denoted by the symbols ‘?:’. It consists of three operands: a condition to test, an expression to return if the condition is true, and an expression to return if the condition is false. Its general syntax is: condition ? expressionOnTrue : expressionOnFalse. Using the ternary operator can help simplify complex “if-else” structures, especially when dealing with simple value assignments based on a condition.

However, it’s essential to use the ternary operator judiciously without overusing it. Although it makes the code more concise, using it excessively in complex situations can lead to difficulties in understanding and maintaining the codebase. Therefore, programmers should strike a balance between using the ternary operator for simplicity and clarity, and employing traditional “if-else” statements for more intricate scenarios.

Table of Contents

C# Ternary Operator Basics

The C# ternary operator, also known as the ?: operator, is a compact way to evaluate a Boolean condition and return one of two expressions based on whether the condition is true or false. It’s a concise alternative to the traditional if-else statement.

The syntax for the ternary operator in C# is as follows:

Here, condition is a Boolean expression that must evaluate to either true or false . If condition evaluates to true , the expression1 will be returned; otherwise, expression2 is returned. Note that the expressions must be of the same or compatible types.

Let’s examine an example to better understand the ternary operator usage:

In this case, the condition is comparing if the remainder of the number divided by 2 equals 0. If the condition is true, it means the number is even, and the isEven variable will be assigned the value true . If the condition is false, the variable will be assigned false .

The ternary operator in C# is not limited to simple values and can be used to return more complex expressions or even method calls. However, it’s crucial to maintain clarity and readability when using this operator, especially in larger codebases.

In summary, the C# ternary operator is a versatile and concise way to evaluate conditions and return the appropriate values or expressions. It’s a useful tool for streamlining code when used correctly and can help make code easier to read and understand.

Usage and Examples

The C# ternary operator, also known as the conditional operator, is a compact and efficient way to simplify if-else statements. It offers a concise syntax that is suitable for simple decision-making scenarios in your code.

For example, consider a scenario where you want to determine whether a number is odd or even and display the result. Using the ternary operator, this can be achieved in just one line of code:

In this example, the ternary operator checks if the remainder of the number when divided by 2 is equal to 0. If the condition is true, it sets the result variable’s value to “Even”; otherwise, it sets the value to “Odd”. The Console.WriteLine function then displays the result.

Another example involves comparing two numbers and determining which one is greater:

Here, the expression x > y evaluates whether x is greater than y . If the condition is true, the result variable will have the value “x is greater than y”. If false, it will have the value “x is less than or equal to y”. Again, Console.WriteLine is used to output the result.

The C# ternary operator is especially helpful in scenarios where you need to simplify your code and make it more readable. However, it’s important to remember that overusing the ternary operator can lead to confusing and difficult-to-read code. It’s best to use it in situations where the logic is simple and its usage improves readability.

Additionally, the ternary operator can be used in combination with other expressions and operators to create more complex logic. For instance, you can nest ternary operators to handle multiple conditions:

In this example, the nested ternary operator checks the relationship between three numbers a , b , and c and reports which one is the largest. The Console.WriteLine function once again displays the result.

In conclusion, when used appropriately, the C# ternary operator can be a valuable tool for creating more efficient and readable code.

Comparison with If-Else Statements

The ternary operator, also known as the conditional operator, is a concise way to perform simple conditional statements in C#. It consists of three expressions, separated by the ? and : symbols, and can be written in a single line. This makes it a popular choice for certain scenarios where brevity is important, but keep in mind that it may not provide the same level of readability as traditional if-else statements.

The syntax of the ternary operator is as follows:

When using an if-else statement, the same logic would be expressed like this:

One key difference between the two is their scope. The ternary operator is an expression, which means it returns a value that can be used in other expressions or assigned to a variable. On the other hand, if-else statements are control structures that do not return values. Therefore, when using a ternary operator, it is important to return values for both the expressionIfTrue and expressionIfFalse parts.

While the ternary operator is concise and can be efficient for simple operations, it is not always appropriate for every case. Below are some considerations when deciding between the two:

  • Readability : For complex or nested conditions, an if-else statement may be more readable and maintainable due to its multi-line structure. Ternary operators can become hard to decipher when multiple conditions are involved.
  • Performance : In general, both the ternary operator and if-else statements have similar performance characteristics. However, there can be minor differences in execution time depending on the specific use case, compiler optimizations, and target framework.
  • Code Brevity : For simple cases, the ternary operator can provide a more succinct representation of the code, which can be beneficial in some situations where brevity is important. This can lead to shorter, cleaner code when used appropriately.

In conclusion, the choice between ternary operators and if-else statements should primarily be based on the specific context and requirements of the code. Both approaches have their advantages and drawbacks, and the programmer should make a conscious decision based on factors such as readability, performance, and code brevity.

Operators, Operands, and Precedence

In C#, operators are symbols that perform actions on operands, which can be variables, literals, or expressions. The ternary operator (?:), also known as the conditional operator, is a concise way to evaluate one of two expressions based on a given Boolean condition. It is right-associative—the operations are grouped starting from the right side.

The ternary operator has three parts: a condition, an output if the condition is true, and an output if the condition is false. The syntax for the ternary operator is as follows:

For example, suppose we want to check if a given temperature is greater than or equal to 20 degrees Celsius:

In this case, tempInCelsius >= 20 is the condition, "Warm" is the output if the condition is true, and "Cold" is the output if the condition is false. The variable weatherDisplay will contain the value “Warm” because the temperature tempInCelsius is greater than or equal to 20.

Precedence refers to the order in which operators are evaluated in an expression. The ternary operator has a lower precedence than comparison operators like greater than (>), equal to (==), and logical operators such as && (AND) and || (OR). Due to the precedence, it is evaluated after these operators in an expression.

Here are some example expressions demonstrating the precedence of the ternary operator:

In the first example, the greater than operator (>) is evaluated before the ternary operator, and the second example evaluates the logical negation operator (!) before the ternary operator.

C# also supports operator overloadability , which means that you can define new behaviors for existing operators for custom types. However, the ternary operator is not overloadable. If you need custom behaviors for conditional expressions, you should use if and else statements or create suitable methods for your custom type.

Type and Conversion in Ternary Expressions

In C#, ternary expressions make use of the ?: operator to create a compact way of handling simple conditional statements. It allows for evaluating a Boolean expression and returning one of two results based on whether the expression is true or false.

One important aspect to consider when using ternary expressions is the type and conversion of the values involved. It’s essential to understand how C# handles these conversions before using the ?: operator in your code.

The ternary operator requires that the second and third expressions share a common type or have an implicit conversion available between them. If there’s no such conversion or common type, the compiler will generate an error. This constraint ensures type safety and helps prevent runtime errors related to type mismatches.

In cases where the second and third expressions are of different types, the C# compiler attempts to apply implicit conversions as needed. An implicit conversion is a type conversion that happens automatically and doesn’t require any explicit casting. For example, an int value can implicitly convert to a double value without any explicit type casting.

However, there are limitations to implicit conversions. If neither the second nor the third expression can be implicitly converted to the other’s type, and they don’t share a common type, a compilation error occurs. This situation requires manual casting or refactoring the code to avoid the error.

Ternary expressions support various types such as numbers, strings, and custom objects as long as they have common types or implicit conversions between them. However, when dealing with void return types, the compiler will generate an error since a ternary expression requires a value to be returned for evaluation.

In summary, understanding the type and conversion of values in ternary expressions is crucial for writing clean and concise code. It ensures type safety, prevents runtime errors related to type mismatches, and makes the code easier to read and understand. When working with the ?: operator, always be mindful of the types involved and potential implicit conversions.

Advanced Usage

The C# ternary operator, also known as the conditional operator, is a concise way to make simple, condition-based assignments. Although its basic usage is intuitive, understanding advanced concepts can further improve its utility within your code.

A common scenario is the use of the ternary operator within a namespace, which helps organize code into logical groupings. Imagine having a utility function that returns a minimum value:

Here, the ternary operator is employed to decide between two values and return the minimum.

When it comes to logical operations, such as AND, OR, and NOT, the ternary operator can be combined with these as well. Consider the following example:

In this code snippet, && (AND) is used along with the ternary operator to evaluate two conditions. You can also use || (OR) and ! (NOT) in similar fashion.

The null coalescing operator ( ?? ) can also be incorporated into ternary operator expressions. The null coalescing operator returns the left-hand operand if it is not null, or the right-hand operand if the left-hand operand is null. For instance:

This block of code can be simplified using the null coalescing operator:

Another advanced usage is nesting ternary operators. This technique should be employed with caution, as it can lead to less readable code. Nested ternary operators allow checking multiple conditions, as shown below:

In summary, the advanced usage of the C# ternary operator includes working within namespaces, using logical operators, employing null coalescing, and utilizing nested ternary operators. Consider each of these techniques when building efficient and concise code structures.

C# Language Specification

The C# language provides a unique decision-making operator known as the ternary conditional operator ?: . This operator is valuable for simplifying code and making it more readable, especially when dealing with small decisions based on boolean conditions.

The ternary conditional operator requires three expressions: a boolean condition, followed by the value to be returned if the condition is true, and finally the value to be returned if the condition is false. The syntax for using the ternary conditional operator is as follows:

For example, let’s consider a situation when we want to determine if a number is even or odd. Using the ternary conditional operator, we can achieve this with a single line of code:

In this example, the condition number % 2 == 0 checks if the remainder of the division of number by 2 is equal to 0. If this condition is true, the value “even” is assigned to the result variable; otherwise, the value “odd” is assigned.

It is essential to know that the ternary conditional operator has lower precedence than most other operators in C#. This means that in expressions containing multiple operations, the ternary operator usually gets evaluated last. For instance, in the following expression:

The operations are evaluated in the following order: multiplication y * z , then addition x + y * z , and finally the ternary operator flag ? a : b . It is crucial to use parentheses to force the desired order of evaluation when necessary.

In summary, the ternary conditional operator in C# is a powerful decision-making tool that can simplify code while maintaining readability. It offers a concise way of making decisions based on boolean conditions, and by understanding its precedence and proper usage, developers can leverage it to write clear and efficient code.

Related posts:

  • Var Keyword in C#: Understanding Its Use and Benefits
  • Asp.net Repeater: A Comprehensive Guide for Efficient Data Binding
  • C# Extension Methods: Simplifying Code and Boosting Efficiency
  • Improved Target Typing In C# 9

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

Study through a pre-planned curriculum designed to help you fast-track your DotNet career and learn from the world’s best collection of DotNet Resources.

Find us on social media:

As Featured On

assignment in ternary operator c#

Contact: [email protected]  | Phone Number: (973) 916-2695 | Address: 288 Rosa Parks Blvd, Paterson, New Jersey 07501, USA

Disclaimer: Efforts are made to maintain reliable data on all information presented. However, this information is provided without warranty. Users should always check the offer provider’s official website for current terms and details. Our site receives compensation from many of the offers listed on the site. Along with key review factors, this compensation may impact how and where products appear across the site (including, for example, the order in which they appear). Our site does not include the entire universe of available offers. Editorial opinions expressed on the site are strictly our own and are not provided, endorsed, or approved by advertisers.

2022 © DotNetCoreTutorials All rights reserved.

assignment in ternary operator c#

Conditional operator(?:) in C#

Conditional operator (?:) in C# is used as a single line if-else assignment statement, it is also known as Ternary Operator in C#. It evaluates a Boolean expression and on the basis of the evaluated True and False value, it executes corresponding statement.

Precisely, conditional operator (?:) can be explained as follows.

It has three operands: condition , consequence and alternative . The conditional expression returns a Boolean value as true or false . If the value is true , then it evaluates the consequence expression. If false , then it evaluates the alternative expression.

Syntax of c onditional operator (?:) in C#

It uses a question mark ( ? ) operator and a colon ( : )  operator , the general format is as follows.

Condition ( Boolean expression ) ? consequence ( if true ) : alternative ( if false )

Lets look at below example, here we are doing a conditional check and based on the true/false, assigning the variable value to taxPercentage  .

In above case, If isSiniorCitizen == true then taxPercentage  will be 20 else it will be 30 , in the above case it sets to 20 since we have already set the boolean value isSiniorCitizen = true  .

Example of (?:) operator in C#

Lets look at an example.

In above example code snippet, the boolean expression String . IsNullOrEmpty ( LastName ) returns True value, so the consequence statement executes, which gives output as “Ramesh” . 

Conditional operator figure 1.0

Lets take another example, where conditional expression returns False value.

In above example, the boolean expression String . IsNullOrEmpty ( LastName  returns False value, so the alternative statement ( FirstName + " " + LastName ) executes, which gives output as “Ramesh Kumar” . 

Conditional operator figure 1.1

Conditional operator(?:) vs Null Coalescing (??) Operator ?

In the case of Null coalescing operator (??) , It checks for the null-ability of first operand and based on that assigns the value. If the first operand value is null then assigns second operand else assigns the first.

Lets have a look at below expression.

In the above example, If y is null then z is assigned to x else y . For more details on Null coalescing operator (??) , please check here . 

We can rewrite above expression using conditional operator (?:) as follows.

Here, if y is null (that means if the expression ( Y == null )  return true) then assign z else assign y to x .

In single line if else statement:

Lets take below if-else statement.

In above if-else statement, boolean expression determines variable assignment. This is the right scenario where we can use Conditional operator (?:) as a replacement of if-else statement.

In above example, here in this case i >= 5   is a True condition, hence this statement  10 * 5 executes and 50 is assigned to x . Lets take below example.

In above example, here condition i >= 5 is  False , hence 10 * 4   executes and 40 is assigned to x .

Nested conditional operator (?:) in C#

In some scenarios, where there are cascading if-else conditions of variable assignment. We can use chaining conditional operators to replace cascading if-else conditions to a single line, by including a conditional expression as a second statement.

Let’s take below example of cascading/nested if-else statement.

Above cascading if-else condition can be re-written as follows.

Share this:

One thought on “ conditional operator(:) in c# ”.

Add Comment

VB will use If(Condition, TruePart, FalsePart) if not same types then IIf can be used.

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Discover more from

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

IMAGES

  1. Ternary Operator in C++

    assignment in ternary operator c#

  2. Ternary Operator (? :) in C# with Examples

    assignment in ternary operator c#

  3. Ternary Operator in C#

    assignment in ternary operator c#

  4. C# Ternary Operator

    assignment in ternary operator c#

  5. C# Ternary Operator Offering a Concise and Powerful Solution

    assignment in ternary operator c#

  6. [Solved] How to use ternary operator in C#

    assignment in ternary operator c#

COMMENTS

  1. ?: operator

    See also. The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false, as the following example shows: C#. Copy. Run.

  2. How to use ternary operator in C#

    10. The ternary operator in just about every language works as an inline if statement: Console.WriteLine((five == 5) ? 'true' : 'false'); (You shouldn't strictly need the inner parens, but I like to include them for clarity.) If the boolean evaluates to true, then the entire expression is equal to the value between the ? and :.

  3. C# ternary (? :) Operator (With Example)

    Then, the ternary operator is used to check if number is even or not. Since, 2 is even, the expression (number % 2 == 0) returns true. We can also use ternary operator to return numbers, strings and characters. Instead of storing the return value in variable isEven, we can directly print the value returned by ternary operator as,

  4. C# Ternary Operator: How to Use it Effectively?

    Definition and Usefulness of C# Ternary Operator. The C# Ternary Operator is quite emerging as a powerful, compact substitute for lengthy if-else statements. Comprising only three operands, it speeds up your coding process like a charm. Its syntax condition ? expr1 : expr2 means: if condition is true, expr1 is executed; otherwise, it's expr2.

  5. C# Short Hand If...Else (Ternary Operator)

    There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements: Syntax Get your own C# Server. variable = (condition) ? expressionTrue : expressionFalse; Instead of writing:

  6. C#

    Example: Ternary operator. int x = 10, y = 100; var result = x > y ? "x is greater than y" : "x is less than y"; Console.WriteLine(result); output: x is less than y. Thus, a ternary operator is short form of if else statement. The above example can be re-write using if else condition, as shown below. Example: Ternary operator replaces if statement.

  7. C#

    Ternary. The C# ternary operator tests a condition. It compares 2 values, and it produces a third value that depends on the result of the comparison. Operator notes. The ternary effect can be accomplished with if-statements or other constructs. The ternary operator provides an elegant and equivalent syntax form to the if-statement.

  8. C# Ternary Operator: Simplify Conditional Expressions

    The C# ternary operator, also known as the conditional operator, is a valuable tool for programmers to write concise and efficient code. This operator evaluates a Boolean expression and returns one of two specified values based on whether the expression is true or false. It serves as a compact alternative to the traditional "if-else ...

  9. Conditional Operator in C#

    Conditional operator (?:) in C# is used as a single line if-else assignment statement, it is also known as Ternary Operator in C#. It evaluates a Boolean expression and on the basis of the evaluated True and False value, it executes corresponding statement.. Precisely, conditional operator (?:) can be explained as follows.

  10. c#

    50. The ternary operator is used to return values and those values must be assigned. Assuming that the methods doThis() and doThat() return values, a simple assignment will fix your problem. If you want to do what you are trying, it is possible, but the solution isn't pretty. int a = 5;