TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Ternary Operator Use

This C# program uses ternary statements. The ternary operator can replace an if-statement.

Ternary operator. The ternary operator tests a condition.

It compares two values. It produces a third value that depends on the result of the comparison. This can be accomplished with if-statements or other constructs.

Tip: The ternary operator provides an elegant and equivalent syntax form to the if-statement.

Example. One common use of the ternary operator is to initialize a variable with the result of the expression. At compile-time, the C# compiler translates the ternary expression into branch statements such as brtrue.

IL

However, the high-level ternary statement is useful because it allows you to condense multiple if-statements and reduce nesting. It does not actually eliminate branching. It simplifies the high-level representation of the branching.

C# program that uses ternary operator

using System;

class Program
{
    static void Main()
    {
	//
	// If the expression is true, set value to 1.
	// Otherwise, set value to -1.
	//
	int value = 100.ToString() == "100" ?
	    1 :
	    -1;

	Console.WriteLine(value);
    }
}

Output

1

The program uses the ternary expression to initialize a variable. If the subexpression evaluates to true, the integer variable with the identifier 'value' has its location on the stack copied to the bit values of the integer 1.

Otherwise: It has its location on the stack copied to the binary representation of -1.

Internally: This code uses branch statements that are defined in the intermediate language.

Return. You can return the result of a ternary statement in a method return statement. The result of evaluating the ternary operator must match the return type of the enclosing method for the compilation to succeed.

Note: The intermediate language generated is equivalent to an if-statement, but the source code contains fewer lines of code.

C# program that returns ternary expression

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine(GetValue("Sam"));
	Console.WriteLine(GetValue("Jane"));
    }

    /// <summary>
    /// Return the value 100 if the name matches, otherwise -1.
    /// </summary>
    static int GetValue(string name)
    {
	return name == "Sam" ? 100 : -1;
    }
}

Output

100
-1

We invoke the GetValue method twice in the Main method. The GetValue method internally executes the intermediate language branching instructions that are equivalent to the logic expressed in the high-level ternary operator.

And: If the parameter to GetValue is equal to the string data in the literal, the integer 100 is returned. Otherwise -1 is returned.

Min, max. One popular use of the ternary operator in C-like languages is to get the minimum or maximum of two numbers or one variable and an integer constant. This approach is still useful in the C# language.

Note: The Math class in the .NET Framework provides the Math.Min and Math.Max methods. These have clearer calling syntax.

Decimal: This type is handled separately by the Math.Max and Math.Min methods. The ternary expression may not be equivalent.

Math.MinMath.Max

Implementation. I disassembled several versions of ternary expressions and found that they are identical to if-statements, with one small difference. The ternary statement sometimes produces code that tests the opposite condition that you would expect.

And: It tests that the subexpression is false instead of testing if it is true. This reorders some of the instructions.

Summary. We looked at the ternary operator. We used it to initialize an integer variable and then used it to return a value. The ternary statement can receive an expression that it first evaluates before proceeding to part after the question mark.

And: We investigated parts of the intermediate language. We saw some additional uses of the ternary statement.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf