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

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

c sharp conditional assignment

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

c sharp conditional assignment

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. Learn more about us .

.NET Tutorials

Database tutorials, javascript tutorials, programming tutorials.

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

The parenthesized condition of the if statement is a Boolean expression . In Listing 4.29 , the condition is highlighted.

Boolean expressions appear within many control flow statements. Their key characteristic is that they always evaluate to true or false . For input < 9 to be allowed as a Boolean expression, it must result in a bool . The compiler disallows x = 42 , for example, because this expression assigns x and results in the value that was assigned instead of checking whether the value of the variable is 42 .

C# eliminates a coding error commonly found in C and C++. In C++, Listing 4.30 is allowed.

Although at first glance this code appears to check whether input equals 9 , Chapter 1 showed that = represents the assignment operator, not a check for equality. The return from the assignment operator is the value assigned to the variable—in this case, 9 . However, 9 is an int , so it does not qualify as a Boolean expression and is not allowed by the C# compiler. The C and C++ languages treat integers that are nonzero as true and integers that are zero as false . C#, by contrast, requires that the condition actually be of a Boolean type; integers are not allowed.

Relational and equality operators determine whether a value is greater than, less than, or equal to another value. Table 4.2 lists all the relational and equality operators. All are binary operators.

The C# syntax for equality uses == , just as many other programming languages do. For example, to determine whether input equals 9 , you use input == 9 . The equality operator uses two equal signs to distinguish it from the assignment operator, = . The exclamation point signifies NOT in C#, so to test for inequality you use the inequality operator, != .

Relational and equality operators always produce a bool value, as shown in Listing 4.31 .

In the full tic-tac-toe program listing, you use the equality operator to determine whether a user has quit. The Boolean expression in Listing 4.32 includes an OR ( || ) logical operator, which the next section discusses in detail.

The logical operators have Boolean operands and produce a Boolean result. Logical operators allow you to combine multiple Boolean expressions to form more complex Boolean expressions. The logical operators are | , || , & , && , and ^ , corresponding to OR, AND, and exclusive OR. The | and & versions of OR and AND are rarely used for Boolean logic, for reasons which we discuss in this section.

In Listing 4.32 , if the user enters quit or presses the Enter key without typing in a value, it is assumed that they want to exit the program. To enable two ways for the user to resign, you can use the logical OR operator, || . The || operator evaluates Boolean expressions and results in a true value if either operand is true (see Listing 4.33 ).

It is not necessary to evaluate both sides of an OR expression, because if one operand is true , the result is known to be true regardless of the value of the other operand. Like all operators in C#, the left operand is evaluated before the right one, so if the left portion of the expression evaluates to true , the right portion is ignored. In the example in Listing 4.33 , if hourOfTheDay has the value 33 , then (hourOfTheDay > 23) evaluates to true and the OR operator ignores the second half of the expression, short-circuiting it. Short-circuiting an expression also occurs with the Boolean AND operator. (Note that the parentheses are not necessary here; the logical operators are of lower precedence than the relational operators. However, it is clearer to the novice reader when the subexpressions are parenthesized for clarity.)

The Boolean AND operator, && , evaluates to true only if both operands evaluate to true . If either operand is false , the result will be false . Listing 4.34 writes a message if the given variable is both greater than 10 and less than 24. 3 Similarly to the OR operator, the AND operator will not always evaluate the right side of the expression. If the left operand is determined to be false , the overall result will be false regardless of the value of the right operand, so the runtime skips evaluating the right operand.

The caret symbol, ^ , is the exclusive OR (XOR) operator. When applied to two Boolean operands, the XOR operator returns true only if exactly one of the operands is true, as shown in Table 4.3 .

Unlike the Boolean AND and Boolean OR operators, the Boolean XOR operator does not short-circuit: It always checks both operands, because the result cannot be determined unless the values of both operands are known. Note that the XOR operator is exactly the same as the Boolean inequality operator.

The logical negation operator , or NOT operator , ! , inverts a bool value. This operator is a unary operator, meaning it requires only one operand. Listing 4.35 demonstrates how it works, and Output 4.16 shows the result.

At the beginning of Listing 4.35 , valid is set to false . You then use the negation operator on valid and assign the value to result .

As an alternative to using an if - else statement to select one of two values, you can use the conditional operator . The conditional operator uses both a question mark and a colon; the general format is as follows:

condition ? consequent : alternative

The conditional operator is a ternary operator because it has three operands: condition , consequent , and alternative . (As it is the only ternary operator in C#, it is often called the ternary operator , but it is clearer to refer to it by its name than by the number of operands it takes.) Like the logical operators, the conditional operator uses a form of short-circuiting. If the condition operator evaluates to true , the conditional operator evaluates only consequent . If the conditional evaluates to false , it evaluates only alternative . The result of the operator is the evaluated expression.

Listing 4.36 illustrates the use of the conditional operator. The full listing of this program appears in of the source code.

The program swaps the current player. To do so, it checks whether the current value is 2 . This is the conditional portion of the conditional expression. If the result of the condition is true , the conditional operator results in the consequent value, 1 . Otherwise, it results in the alternative value, 2 . Unlike in an if statement, the result of the conditional operator must be assigned (or passed as a parameter); it cannot appear as an entire statement on its own.

Prior to C# 9.0, the language required that the output (the consequent and alternative) expressions in a conditional operator be consistently typed and that the consistent type be determined without examination of the surrounding context of the expression, including the resulting type assigned. However, C# 9.0 added support for target-typed conditional expressions so that even if the consequent and alternative expressions are of different types (such as string and int ) and neither is convertible to the other, the statement is still allowed if both types will implicitly cast to the targeted type. For example, even if you have object result = condition ? "abc" : 123; , the C# compiler will allow it because both the potential conditional output types will implicitly cast to object .

________________________________________

  • p.key == item.key) && !currentPage.some(p => p.level > item.level), }" > p.key == item.key) && !currentPage.some(p => p.level > item.level), }" :href="item.href"> Introduction
  • p.key == item.key) && !currentPage.some(p => p.level > item.level), }" > p.key == item.key), }" :href="item.href"> {{item.title}}

Conditional Statements in C#

Master the art of writing flexible code with C#’s powerful conditional statements. Learn how to use if-else, switch, and ternary operators to control the flow of your program and create robust, maintainable software.

Conditional statements are a fundamental part of any programming language, and C# is no exception. These statements allow you to execute different blocks of code based on certain conditions. In this article, we’ll explore the different types of conditional statements available in C#, as well as some best practices for using them effectively.

If Statements

The most basic type of conditional statement in C# is the if statement. Here’s an example:

In this example, condition is a boolean expression that evaluates to either true or false . If condition is true , the code inside the if statement will be executed. If condition is false , the code inside the if statement will be skipped.

Here are some examples of if statements in C#:

Else Statements

In some cases, you may want to execute different code depending on whether a condition is true or false. This is where else statements come in. Here’s an example:

In this example, the code inside the if statement will be executed if condition is true . The code inside the else statement will be executed if condition is false .

Here’s an example of an else statement in C#:

Switch Statements

Switch statements are another type of conditional statement in C#. Here’s an example:

In this example, expression is a variable or expression that evaluates to one of the case values. The code inside each case block will be executed if expression evaluates to that value. The default block will be executed if expression does not match any of the case values.

Here’s an example of a switch statement in C#:

Ternary Operator

The ternary operator is a shorthand way of writing an if statement with a simple condition. Here’s an example:

In this example, condition is a boolean expression that evaluates to either true or false . If condition is true , trueStatement will be executed. If condition is false , falseStatement will be executed.

Here’s an example of the ternary operator in C#:

Best Practices

When using conditional statements in your C# code, it’s important to follow some best practices:

  • Use clear and descriptive variable names for your conditions and statements. This will make your code easier to understand and maintain.
  • Keep your if statements and else statements as simple as possible. Complex conditions can make your code difficult to read and understand.
  • Use the ternary operator sparingly. While it can be a useful shorthand, it can also make your code more difficult to read if used too frequently.
  • Use switch statements instead of multiple if statements when you need to match against multiple values. This will make your code more concise and easier to read.

In conclusion, conditional statements are an essential part of any programming language, and C# is no exception. By understanding the different types of conditional statements available in C#, as well as some best practices for using them effectively, you’ll be well on your way to writing clean, readable, and maintainable C# code.

IMAGES

  1. C# Conditional Operators

    c sharp conditional assignment

  2. Conditional Statement in C Sharp, if else , Switch, Else if statement

    c sharp conditional assignment

  3. conditional statements in c# (sharp)

    c sharp conditional assignment

  4. C Sharp Conditional statements practice for beginners

    c sharp conditional assignment

  5. C Sharp

    c sharp conditional assignment

  6. Conditional Statement in C#

    c sharp conditional assignment

VIDEO

  1. C# Syntax Basics

  2. C# Programming Tutorial Videos Lesson 3: If and Else Statements

  3. C# Tutorial

  4. Code.org Lesson 7.1C Conditionals Practice

  5. Episode 7 Conditional Statement C Sharp C#

  6. Console Application: Conditional Statements C Sharp

COMMENTS

  1. ?: operator

    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; See also. Simplify conditional expression (style rule IDE0075) C# operators and ...

  2. c#

    The ternary operator (?:) is not designed for control flow, it's only designed for conditional assignment. If you need to control the flow of your program, use a control structure, such as if/else. Share. Improve this answer. ... Operator (C# Reference) The conditional operator (?:) returns one of two values depending on the value of a Boolean ...

  3. c#

    Third, the feature is more general than just "if", as I noted. Fourth, there is a trend in C# since C# 3.0 to make more and more things that required a statement context instead require an expression context; this helps with functional-style programming. See the language design notes for more details. -

  4. C# ?: Ternary Operator (Conditional Operator)

    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.

  5. C#'s conditional operator (?:) explained · Kodify

    ApplCount():0); Here we use the Console.WriteLine()method to print the number of appliances we need for an order. We base that count on the isKitchenBoolean variable. When that one is true, the conditional operator executes ApplCount()and returns that method's value. Should that variable be false, the operator returns 0.

  6. Conditional operator(?:) in C#

    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 ...

  7. 3 ways to update C# variables conditionally · Kodify

    1) Set variable with if statement. 2) Update variable with if/else statement. 3) Set variable with conditional operator. Two quick ways to set variable conditionally. Replace if/else with default value. Replace if/else with conditional operator. Summary. Most variables have a different value at various stages in our program's execution. A ...

  8. C#

    In C#, conditionals compare inputs and return a boolean value indicating whether it evaluates to true or false. Conditional statements include the if, else and else if statements. A shorthand for the if/else statement is the conditional or ternary operator.. If Statement. An if statement evaluates a condition that, when true, will run a code block that follows.

  9. Essential C#: Conditional Operator (?:)

    The program swaps the current player. To do so, it checks whether the current value is 2. This is the conditional portion of the conditional expression. If the result of the condition is true, the conditional operator results in the consequent value, 1. Otherwise, it results in the alternative value, 2. Unlike in an if statement, the result of ...

  10. Replace if/else C# code with conditional operator · Kodify

    This has the conditional operator always either execute its second or third expression. The logic of the conditional operator is: "if this is true, do the first; otherwise, do the second." This has the operator behave like an if/else statement. That is, the conditional operator first evaluates a true/false condition.

  11. C# Conditional Operator (With Step-By-Step Video Tutorial)

    Actually, this operator is a shorthand method of writing a simple single line if else statement. The C# conditional operator makes your code shorter and easier to read. It uses three operands on one line. The first operand is a Boolean expression that evaluates to true or false. If the expression is true, the value of the second operand is ...

  12. Understanding Conditional Statements in C#

    Conditional statements are a fundamental concept in programming that allows developers to control the flow of their code based on certain conditions. In C#, conditional statements are achieved through a variety of keywords and operators that allow you to check for certain conditions and execute specific blocks of code based on the results.

  13. Conditional Statements in C#

    The most basic type of conditional statement in C# is the if statement. Here's an example: // code to execute if condition is true. In this example, condition is a boolean expression that evaluates to either true or false. If condition is true, the code inside the if statement will be executed.

  14. c#

    However, depending on your C# version, there are workarounds for your particular use case. C# 7: Since C# 7, arguments to out parameters in a method call can be declared inline: Console.WriteLine($"{s} has been parsed as {i}."); Console.WriteLine($"Unable to parse {s}."); so you could work around your problem by designing a custom RegexTryMatch ...

  15. c#

    21. The null propagation operator returns a value. And since you must have a variable on the left hand side of an assignment, and not a value, you cannot use it in this way. Sure, you could make things shorter by using the tenary operator, but that, on the other hand, doesn't really help the readability aspect.