assignment in conditional expression 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

assignment in conditional expression 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 conditional expression 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. Learn more about us .

.NET Tutorials

Database tutorials, javascript tutorials, programming tutorials.

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

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.

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

C# operator

last modified July 5, 2023

In this article we cover C# operators.

Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands. The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators.

An operator is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data. An operand is one of the inputs (arguments) of an operator.

C# operator list

The following table shows a set of operators used in the C# language.

An operator usually has one or two operands. Those operators that work with only one operand are called unary operators . Those who work with two operands are called binary operators . There is also one ternary operator ?: , which works with three operands.

Certain operators may be used in different contexts. For example the + operator. From the above table we can see that it is used in different cases. It adds numbers, concatenates strings or delegates; indicates the sign of a number. We say that the operator is overloaded .

C# unary operators

C# unary operators include: +, -, ++, --, cast operator (), and negation !.

C# sign operators

There are two sign operators: + and - . They are used to indicate or change the sign of a value.

The + and - signs indicate the sign of a value. The plus sign can be used to indicate that we have a positive number. It can be omitted and it is mostly done so.

The minus sign changes the sign of a value.

C# increment and decrement operators

Incrementing or decrementing a value by one is a common task in programming. C# has two convenient operators for this: ++ and -- .

The above two pairs of expressions do the same.

In the above example, we demonstrate the usage of both operators.

We initiate the x variable to 6. Then we increment x two times. Now the variable equals to 8.

We use the decrement operator. Now the variable equals to 7.

C# explicit cast operator

The explicit cast operator () can be used to cast a type to another type. Note that this operator works only on certain types.

In the example, we explicitly cast a float type to int .

Negation operator

The negation operator (!) reverses the meaning of its operand.

In the example, we build a negative condition: it is executed if the inverse of the expression is valid.

C# assignment operator

The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In mathematics, the = operator has a different meaning. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.

Here we assign a number to the x variable.

The previous expression does not make sense in mathematics. But it is legal in programming. The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x .

This code example results in syntax error. We cannot assign a value to a literal.

C# concatenating strings

The + operator is also used to concatenate strings.

We join three strings together using string concatenation operator.

C# arithmetic operators

The following is a table of arithmetic operators in C#.

The following example shows arithmetic operations.

In the preceding example, we use addition, subtraction, multiplication, division, and remainder operations. This is all familiar from the mathematics.

The % operator is called the remainder or the modulo operator. It finds the remainder of division of one number by another. For example, 9 % 4 , 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1.

Next we show the distinction between integer and floating point division.

In the preceding example, we divide two numbers.

In this code, we have done integer division. The returned value of the division operation is an integer. When we divide two integers the result is an integer.

If one of the values is a double or a float, we perform a floating point division. In our case, the second operand is a double so the result is a double.

C# Boolean operators

In C#, we have three logical operators. The bool keyword is used to declare a Boolean value.

Boolean operators are also called logical.

Many expressions result in a boolean value. Boolean values are used in conditional statements.

Relational operators always result in a boolean value. These two lines print false and true.

The body of the if statement is executed only if the condition inside the parentheses is met. The y > x returns true, so the message "y is greater than x" is printed to the terminal.

The true and false keywords represent boolean literals in C#.

Example shows the logical and operator. It evaluates to true only if both operands are true.

Only one expression results in True .

The logical or || operator evaluates to true, if either of the operands is true.

If one of the sides of the operator is true, the outcome of the operation is true.

Three of four expressions result in true.

The negation operator ! makes true false and false true.

The example shows the negation operator in action.

The || , and && operators are short circuit evaluated. Short circuit evaluation means that the second argument is only evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of the logical and evaluates to false, the overall value must be false; and when the first argument of logical or evaluates to true, the overall value must be true. Short circuit evaluation is used mainly to improve performance.

An example may clarify this a bit more.

We have two methods in the example. They are used as operands in boolean expressions.

The One method returns false . The short circuit && does not evaluate the second method. It is not necessary. Once an operand is false , the result of the logical conclusion is always false . Only "Inside one" is only printed to the console.

In the second case, we use the || operator and use the Two method as the first operand. In this case, "Inside two" and "Pass" strings are printed to the terminal. It is again not necessary to evaluate the second operand, since once the first operand evaluates to true , the logical or is always true .

C# relational operators

Relational operators are used to compare values. These operators always result in boolean value.

Relational operators are also called comparison operators.

In the code example, we have four expressions. These expressions compare integer values. The result of each of the expressions is either true or false. In C# we use == to compare numbers. Some languages like Ada, Visual Basic, or Pascal use = for comparing numbers.

C# bitwise operators

Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal, or hexadecimal symbols are only notations of the same number. Bitwise operators work with bits of a binary number. Bitwise operators are seldom used in higher level languages like C#.

The bitwise negation operator changes each 1 to 0 and 0 to 1.

The operator reverts all bits of a number 7. One of the bits also determines, whether the number is negative or not. If we negate all the bits one more time, we get number 7 again.

The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.

The first number is a binary notation of 6, the second is 3, and the result is 2.

The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if either of the corresponding bits in the operands is 1.

The result is 00110 or decimal 7.

The bitwise exclusive or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.

The result is 00101 or decimal 5.

C# compound assignment operators

The compound assignment operators consist of two operators. They are shorthand operators.

The += compound operator is one of these shorthand operators. The above two expressions are equal. Value 3 is added to the a variable.

Other compound operators are:

In the example, we use two compound operators.

The a variable is initiated to one. 1 is added to the variable using the non-shorthand notation.

Using a += compound operator, we add 5 to the a variable. The statement is equal to a = a + 5; .

Using the *= operator, the a is multiplied by 3. The statement is equal to a = a * 3; .

C# new operator

The new operator is used to create objects and invoke constructors.

In the example, we create a new custom object and a array of integers utilizing the new operator.

This is a constructor. It is called at the time of the object creation.

C# access operator

The access operator [] is used with arrays, indexers, and attributes.

In the example, we use the [] operator to get an element of an array, value of a dictionary pair, and activate a built-in attribute.

We define an array of integers. We get the first element with vals[0] .

A dictionary is created. With domains["de"] , we get the value of the pair that has the "de" key.

We active the built-in Obsolete attribute. The attribute issues a warning.

When we run the program, it produces the warning: warning CS0618: 'oldMethod()' is obsolete: 'Don't use OldMethod, use NewMethod instead' .

C# index from end operator ^

The index from end operator ^ indicates the element position from the end of a sequence. For instance, ^1 points to the last element of a sequence and ^n points to the element with offset length - n .

In the example, we apply the operator on an array and a string.

We print the last and the last but one element of the array.

We print the last letter of the word.

C# range operator ..

The .. operator specifies the start and end of a range of indices as its operands. The left-hand operand is an inclusive start of a range. The right-hand operand is an exclusive end of a range.

Operands of the .. operator can be omitted to get an open-ended range.

In the example, we use the .. operator to get array slices.

We create an array slice from index 1 till index 4; the last index 4 is not included.

Here we esentially create a copy of the array.

C# type information

Now we concern ourselves with operators that work with types.

The sizeof operator is used to obtain the size in bytes for a value type. The typeof is used to obtain the System.Type object for a type.

We use the sizeof and typeof operators.

We can see that the int type is an alias for System.Int32 and the float is an alias for the System.Single type.

The is operator checks if an object is compatible with a given type.

We create two objects from user defined types.

We have a Base and a Derived class. The Derived class inherits from the Base class.

Base equals Base and so the first line prints True. The Base is also compatible with Object type. This is because each class inherits from the mother of all classes — the Object class.

The derived object is compatible with the Base class because it explicitly inherits from the Base class. On the other hand, the _base object has nothing to do with the Derived class.

The as operator is used to perform conversions between compatible reference types. When the conversion is not possible, the operator returns null. Unlike the cast operation which raises an exception.

In the above example, we use the as operator to perform casting.

We try to cast various types to the string type. But only once the casting is valid.

C# operator precedence

The operator precedence tells us which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions.

What is the outcome of the following expression, 28 or 40?

Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.

To change the order of evaluation, we can use parentheses. Expressions inside parentheses are always evaluated first.

The following table shows common C# operators ordered by precedence (highest precedence first):

Operators on the same row of the table have the same precedence.

In this code example, we show a few expressions. The outcome of each expression is dependent on the precedence level.

This line prints 28. The multiplication operator has a higher precedence than addition. First, the product of 5*5 is calculated, then 3 is added.

In this case, the negation operator has a higher precedence. First, the first true value is negated to false, then the | operator combines false and true, which gives true in the end.

C# associativity rule

Sometimes the precedence is not satisfactory to determine the outcome of an expression. There is another rule called associativity . The associativity of operators determines the order of evaluation of operators with the same precedence level.

What is the outcome of this expression, 9 or 1? The multiplication, deletion and the modulo operator are left to right associated. So the expression is evaluated this way: (9 / 3) * 3 and the result is 9.

Arithmetic, boolean, relational, and bitwise operators are all left to right associated.

On the other hand, the assignment operator is right associated.

In the example, we have two cases where the associativity rule determines the expression.

The assignment operator is right to left associated. If the associativity was left to right, the previous expression would not be possible.

The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and than the compound assignment operator is applied.

C# null-conditional operator

A null-conditional operator applies a member access, ?. , or element access, ?[] , operation to its operand only if that operand evaluates to non-null. If the operand evaluates to null , the result of applying the operator is null.

In the example, we have a User class with two members: Name and Occupation . We access the name member of the objects with the help of the ?. operator.

We have a list of users. One of them is initialized with null values.

We use the ?. to access the Name member and call the ToUpper method. The ?. prevents the System.NullReferenceException by not calling the ToUpper on the null value.

In the following example, we use the ?[] operator. The operator allows to place null values into a collection.

In this example, we have a null value in an array. We prevent the System.NullReferenceException by applying the ?. operator on the array elements.

C# null-coalescing operator

The null-coalescing operator ?? is used to define a default value for a nullable type. It returns the left-hand operand if it is not null; otherwise it returns the right operand. When we work with databases, we often deal with absent values. These values come as nulls to the program. This operator is a convenient way to deal with such situations.

An example program for null-coalescing operator.

Two nullable int types are initiated to null . The int? is a shorthand for Nullable<int> . It allows to have null values assigned to int types.

We want to assign a value to z variable. But it must not be null . This is our requirement. We can easily use the null-coalescing operator for that. In case both x and y variables are null, we assign -1 to z .

C# null-coalescing assignment operator

The null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null . The ??= operator does not evaluate its right-hand operand if the left-hand operand evaluates to non-null. It is available in C# 8.0 and later.

In the example, we use the null-coalescing assignment operator on a list of integer values.

First, the list is assigned to null .

We use the ??= to assign a new list object to the variable. Since it is null , the list is assigned.

We add some values to the list and print its contents.

We try to assign a new list object to the variable. Since the variable is not null anymore, the list is not assigned.

C# ternary operator

The ternary operator ?: is a conditional operator. It is a convenient operator for cases where we want to pick up one of two values, depending on the conditional expression.

If cond-exp is true, exp1 is evaluated and the result is returned. If the cond-exp is false, exp2 is evaluated and its result is returned.

In most countries the adulthood is based on your age. You are adult if you are older than a certain age. This is a situation for a ternary operator.

First the expression on the right side of the assignment operator is evaluated. The first phase of the ternary operator is the condition expression evaluation. So if the age is greater or equal to 18, the value following the ? character is returned. If not, the value following the : character is returned. The returned value is then assigned to the adult variable.

A 31 years old person is adult.

C# Lambda operator

The => token is called the lambda operator. It is an operator taken from functional languages. This operator can make the code shorter and cleaner. On the other hand, understanding the syntax may be tricky. Especially if a programmer never used a functional language before.

Wherever we can use a delegate, we also can use a lambda expression. A definition for a lambda expression is: a lambda expression is an anonymous function that can contain expressions and statements. On the left side we have a group of data and on the right side an expression or a block of statements. These statements are applied on each item of the data.

In lambda expressions we do not have a return keyword. The last statement is automatically returned. And we do not need to specify types for our parameters. The compiler will guess the correct parameter type. This is called type inference.

We have a list of integer numbers. We print all numbers that are greater than 3.

We have a generic list of integers.

Here we use the lambda operator. The FindAll method takes a predicate as a parameter. A predicate is a special kind of a delegate that returns a boolean value. The predicate is applied for all items of the list. The val is an input parameter specified without a type. We could explicitly specify the type but it is not necessary.

The compiler will expect an int type. The val is a current input value from the list. It is compared if it is greater than 3 and a boolean true or false is returned. Finally, the FindAll will return all values that met the condition. They are assigned to the sublist collection.

The items of the sublist collection are printed to the terminal.

Values from the list of integers that are greater than 3.

This is the same example. We use a anonymous delegate instead of a lambda expression.

C# calculating prime numbers

We are going to calculate prime numbers.

In the above example, we deal with many various operators. A prime number (or a prime) is a natural number that has exactly two distinct natural number divisors: 1 and itself. We pick up a number and divide it by numbers, from 1 up to the picked up number. Actually, we do not have to try all smaller numbers; we can divide by numbers up to the square root of the chosen number. The formula will work. We use the remainder division operator.

We calculate primes from these numbers.

By definition, 1 is not a prime

We skip the calculations for 2 and 3: they are primes. Note the usage of the equality and conditional or operators. The == has a higher precedence than the || operator. So we do not need to use parentheses.

We are OK if we only try numbers smaller than the square root of a number in question. It was mathematically proven that it is sufficient to take into account values up to the square root of the number in question.

This is a while loop. The i is the calculated square root of the number. We use the decrement operator to decrease the i by one each loop cycle. When the i is smaller than 1, we terminate the loop. For example, we have number 9. The square root of 9 is 3. We divide the 9 number by 3 and 2.

This is the core of the algorithm. If the remainder division operator returns 0 for any of the i values then the number in question is not a prime.

C# operators and expressions

In this article we covered C# operators.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials .

Codebuns

  • C# Tutorial
  • Python Tutorial
  • WordPress Tutorial

C# Conditional Operator

C# provides a conditional operator , which is sometimes called C# ternary or question operator . The C# conditional operator “?:” uses the Boolean value of an expression to determine which two other expressions must be calculated and returned as a result. 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 returned; otherwise, the value of the third is returned.

The syntax works like this:

Here, the Condition is evaluated to obtain a Boolean value, and the result of the operator is either expression1 or expression2 based on this value. In other words, if Condition is true, expression1 is evaluated and becomes the result of the operation. Otherwise, expression2 is evaluated and becomes the result of the operation. A conditional expression never evaluates both expression1 and expression2 .

The ternary conditional operator is right-associative; meaning, it is evaluated from right to left.

Restrictions

  • If you want to return a value, then use a conditional statement. Otherwise, use an if-else statement .
  • The operand1 and operand2 type must be the same, or an implicit conversion must exist from one type to the other.
  • C# conditional operator can only be used in assignment statements.

In the above code, the result of the ternary operator is one of two strings, both of which may be assigned to status. The choice of which string to assign depends on the value of the loggedIn variable being true or false. In this case, a value of true results in the first string being assigned, and a value of false results in the second string being assigned.

The above code is equivalent to the following:

User is Online

If conditional expression (number % 2 == 0) in the above example evaluates to true, the string “Even” is returned; Otherwise, string “Odd” . Thus, this statement with the conditional operator performs essentially the same task as the first if-else statement .

a is greater than b a is less than b a is equal to b a is not equal to b 8

Operators in C# can be separated into different categories. Some of them are listed below:

  • C# Arithmetic Operator
  • C# Relational Operator
  • C# Boolean Logical Operator
  • C# Assignment Operators

C# Reference | Microsoft Docs

  • C# conditional operator

Also On Codebuns

C# Programming Basics for Absolute Beginners

C# for Absolute Beginners: The Basics

C# Online Editors

C# Online Editors

C# Variables

C# Variables

C# DataTypes

C# DataTypes

All tutorial topics.

This browser is no longer supported.

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

Member access operators and expressions - the dot, indexer, and invocation operators.

  • 14 contributors

You use several operators and expressions to access a type member. These operators include member access ( . ), array element or indexer access ( [] ), index-from-end ( ^ ), range ( .. ), null-conditional operators ( ?. and ?[] ), and method invocation ( () ). These include the null-conditional member access ( ?. ), and indexer access ( ?[] ) operators.

  • . (member access) : to access a member of a namespace or a type
  • [] (array element or indexer access) : to access an array element or a type indexer
  • ?. and ?[] (null-conditional operators) : to perform a member or element access operation only if an operand is non-null
  • () (invocation) : to call an accessed method or invoke a delegate
  • ^ (index from end) : to indicate that the element position is from the end of a sequence
  • .. (range) : to specify a range of indices that you can use to obtain a range of sequence elements

Member access expression .

You use the . token to access a member of a namespace or a type, as the following examples demonstrate:

  • Use . to access a nested namespace within a namespace, as the following example of a using directive shows:
  • Use . to form a qualified name to access a type within a namespace, as the following code shows:

Use a using directive to make the use of qualified names optional.

  • Use . to access type members , static and non-static, as the following code shows:

You can also use . to access an extension method .

Indexer operator []

Square brackets, [] , are typically used for array, indexer, or pointer element access.

Array access

The following example demonstrates how to access array elements:

If an array index is outside the bounds of the corresponding dimension of an array, an IndexOutOfRangeException is thrown.

As the preceding example shows, you also use square brackets when you declare an array type or instantiate an array instance.

For more information about arrays, see Arrays .

Indexer access

The following example uses the .NET Dictionary<TKey,TValue> type to demonstrate indexer access:

Indexers allow you to index instances of a user-defined type in the similar way as array indexing. Unlike array indices, which must be integer, the indexer parameters can be declared to be of any type.

For more information about indexers, see Indexers .

Other usages of []

For information about pointer element access, see the Pointer element access operator [] section of the Pointer related operators article.

You also use square brackets to specify attributes :

Null-conditional operators ?. and ?[]

A null-conditional operator applies a member access ( ?. ) or element access ( ?[] ) operation to its operand only if that operand evaluates to non-null; otherwise, it returns null . That is:

If a evaluates to null , the result of a?.x or a?[x] is null .

If a evaluates to non-null, the result of a?.x or a?[x] is the same as the result of a.x or a[x] , respectively.

If a.x or a[x] throws an exception, a?.x or a?[x] would throw the same exception for non-null a . For example, if a is a non-null array instance and x is outside the bounds of a , a?[x] would throw an IndexOutOfRangeException .

The null-conditional operators are short-circuiting. That is, if one operation in a chain of conditional member or element access operations returns null , the rest of the chain doesn't execute. In the following example, B isn't evaluated if A evaluates to null and C isn't evaluated if A or B evaluates to null :

If A might be null but B and C wouldn't be null if A isn't null, you only need to apply the null-conditional operator to A :

In the preceding example, B isn't evaluated and C() isn't called if A is null. However, if the chained member access is interrupted, for example by parentheses as in (A?.B).C() , short-circuiting doesn't happen.

The following examples demonstrate the usage of the ?. and ?[] operators:

The first of the preceding two examples also uses the null-coalescing operator ?? to specify an alternative expression to evaluate in case the result of a null-conditional operation is null .

If a.x or a[x] is of a non-nullable value type T , a?.x or a?[x] is of the corresponding nullable value type T? . If you need an expression of type T , apply the null-coalescing operator ?? to a null-conditional expression, as the following example shows:

In the preceding example, if you don't use the ?? operator, numbers?.Length < 2 evaluates to false when numbers is null .

The ?. operator evaluates its left-hand operand no more than once, guaranteeing that it cannot be changed to null after being verified as non-null.

The null-conditional member access operator ?. is also known as the Elvis operator.

Thread-safe delegate invocation

Use the ?. operator to check if a delegate is non-null and invoke it in a thread-safe way (for example, when you raise an event ), as the following code shows:

That code is equivalent to the following code:

The preceding example is a thread-safe way to ensure that only a non-null handler is invoked. Because delegate instances are immutable, no thread can change the object referenced by the handler local variable. In particular, if the code executed by another thread unsubscribes from the PropertyChanged event and PropertyChanged becomes null before handler is invoked, the object referenced by handler remains unaffected.

Invocation expression ()

Use parentheses, () , to call a method or invoke a delegate .

The following example demonstrates how to call a method, with or without arguments, and invoke a delegate:

You also use parentheses when you invoke a constructor with the new operator.

Other usages of ()

You also use parentheses to adjust the order in which to evaluate operations in an expression. For more information, see C# operators .

Cast expressions , which perform explicit type conversions, also use parentheses.

Index from end operator ^

Index and range operators can be used with a type that is countable . A countable type is a type that has an int property named either Count or Length with an accessible get accessor. Collection expressions also rely on countable types.

The ^ operator indicates the element position from the end of a sequence. For a sequence of length length , ^n points to the element with offset length - n from the start of a sequence. For example, ^1 points to the last element of a sequence and ^length points to the first element of a sequence.

As the preceding example shows, expression ^e is of the System.Index type. In expression ^e , the result of e must be implicitly convertible to int .

You can also use the ^ operator with the range operator to create a range of indices. For more information, see Indices and ranges .

Beginning with C# 13, the Index from the end operator can be used in an object initializer.

Range operator ..

The .. operator specifies the start and end of a range of indices as its operands. The left-hand operand is an inclusive start of a range. The right-hand operand is an exclusive end of a range. Either of the operands can be an index from the start or from the end of a sequence, as the following example shows:

As the preceding example shows, expression a..b is of the System.Range type. In expression a..b , the results of a and b must be implicitly convertible to Int32 or Index .

Implicit conversions from int to Index throw an ArgumentOutOfRangeException when the value is negative.

You can omit any of the operands of the .. operator to obtain an open-ended range:

  • a.. is equivalent to a..^0
  • ..b is equivalent to 0..b
  • .. is equivalent to 0..^0

The following table shows various ways to express collection ranges:

The following example demonstrates the effect of using all the ranges presented in the preceding table:

For more information, see Indices and ranges .

The .. token is also used as the spread operator in a collection expression.

Operator overloadability

The . , () , ^ , and .. operators can't be overloaded. The [] operator is also considered a non-overloadable operator. Use indexers to support indexing with user-defined types.

C# language specification

For more information, see the following sections of the C# language specification :

  • Member access
  • Element access
  • Null-conditional member access
  • Invocation expressions

For more information about indices and ranges, see the feature proposal note .

  • Use index operator (style rule IDE0056)
  • Use range operator (style rule IDE0057)
  • Use conditional delegate call (style rule IDE1005)
  • C# operators and expressions
  • ?? (null-coalescing operator)
  • :: operator

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

IMAGES

  1. C# Conditional Operators

    assignment in conditional expression c#

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

    assignment in conditional expression c#

  3. Conditional Operator in C

    assignment in conditional expression c#

  4. Conditional Operators in C#

    assignment in conditional expression c#

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

    assignment in conditional expression c#

  6. Conditional Operator in C

    assignment in conditional expression c#

VIDEO

  1. C#

  2. final English assignment

  3. C#

  4. Conditional and selected signal assignment statements

  5. Use Switch Expressions in Unity to make your code more readable

  6. C/C++, Declaring variables, assigning values, variables usage, and mathematical expression

COMMENTS

  1. c#

    The problem (with the syntax) is not with the assignment, as the assignment operator in C# is a valid expression. Rather, it is with the desired declaration as declarations are statements. If I must write code like that I will sometimes (depending upon the larger context) write the code like this:

  2. ?: operator

    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.

  3. IDE0045: Use conditional expression for assignment

    Overview. This style rule concerns the use of a ternary conditional expression versus an if-else statement for assignments that require conditional logic.. Options. Options specify the behavior that you want the rule to enforce. For information about configuring options, see Option format.. dotnet_style_prefer_conditional_expression_over_assignment

  4. c#

    The expression. a ? b : c evaluates to b if a is true and evaluates to c if a is false. ... 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. ... (C# Reference) The conditional operator (?:) returns one of two values ...

  5. Assignment operators

    Assignment operators (C# reference) The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the ...

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

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

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

  9. Ternary conditional operator

    In C#, if condition is true, first expression is evaluated and becomes the result; if false, ... in this case we can use a conditional assignment expression, or a function call. Bear in mind also that some types allow initialization, but do not allow assignment, or even that the assignment operator and the constructor do totally different ...

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

  11. C# operator

    The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and than the compound assignment operator is applied. $ dotnet run 0 0 0 0 0 C# null-conditional operator

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

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

  14. Expressions

    In C# the binding of an operation is usually determined at compile-time, based on the compile-time type of its subexpressions. ... Deconstruction is used when the target of a simple assignment is a tuple expression, in order to obtain values to assign to each of that tuple's elements. ... For a null conditional expression where the result ...

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

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

    The conditional operator works on three values. The first is a Boolean true/false expression. When that expression is true, the operator executes its second value. And when that true/false expression is false, the conditional operator runs the third and last value (Asad & Ali, 2017; Stephens, 2014). This has the conditional operator always ...

  17. C# operators and expressions

    The simplest C# expressions are literals (for example, integer and real numbers) and names of variables. You can combine them into complex expressions by using operators. Operator precedence and associativity determine the order in which the operations in an expression are performed. You can use parentheses to change the order of evaluation ...

  18. c#

    I would say that you already know what the problem is, readability.The expectation is that you're writing a comparison, it's an if-statement after all, but the consequence is that you're also doing an assignment, so something that checks something also becomes something that changes something.

  19. Member access and null-conditional operators and expressions:

    The null-conditional operators are short-circuiting. That is, if one operation in a chain of conditional member or element access operations returns null, the rest of the chain doesn't execute. In the following example, B isn't evaluated if A evaluates to null and C isn't evaluated if A or B evaluates to null: C#. Copy.