Asp.net C # condition (ternary) operator (? :) Introduction

Source: Internet
Author: User

Ternary operator "? : ", Syntax: condition expression? Expression 1: Expression 2;
This operation first calculates the value of the condition expression (bool type). If it is true, expression 1 is called, and expression 2 is called when it is flase. The logic is: "If it is true, execute the first, otherwise execute the second ."

Syntax

Test? Expression1: expression2


Test
Any Boolean expression.

Expression1
Expression returned when test is true. It may be a funny expression.

Expression2
Expression returned when test is false. It may be a funny expression.


Instance

The code is as follows: Copy code

A = 3> 4? 3: 4; the output is 4.
A = 3 <4? 3: 4; the output is 3.


 

Instance

The code is as follows: Copy code

Int lenth = 10;

String s;

S = (lenth> 16? "Jihua.cnblogs.com": "Scheduler ");

Console. WriteLine (s );

Here, condition is the Boolean expression to be calculated, true_value is the value returned when condition is true, and false_value is the value returned when condition is false. Jihua.cnblogs.com


In this example, if it is later than six o'clock P.M., a string containing "Good evening." is created. The equivalent code for using the if... else statement is as follows:

The code is as follows: Copy code

Var now = new Date ();
Var greeting = "Good ";
If (now. getHours ()> 17)
Greeting + = "evening .";
Else
Greeting + = "day .";


Properly using the ternary operator can make the program very concise.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.