简体   繁体   中英

Can anyone tell me what exactly this code means in c#?

Particularly the symbols ? : And how can I use them in other ways

Console.WriteLine("The rectangle with edges [{0},{1}] is {2}a square" ,
                r3.Edge1, r3.Edge2, (r3.IsSquare()) ? "" : "not ");

Simply said conditional operator (?) does following ,

If condition is true , first_expression is evaluated and becomes the result. If condition is false , second_expression is evaluated and becomes the result

And inputs are given in following format,

condition ? first_expression : second_expression;

In your case parameters are as follow ,

  condition  =  r3.IsSquare()  // <= return a Boolean I guess
  first_expression = ""    // Empty string
  second_expression = not  // word `not` 

So in your case what does code (r3.IsSquare()) ? "" : "not ") (r3.IsSquare()) ? "" : "not ") does,

  • If r3 is a square, output is "" which is empty string.
  • If r3 is not a square , output is the word not

Note that method IsSquare() called upon r3 should return a Boolean (true or false) value.

Same condition evaluated on a console program,

    // if r3.IsSquare() return true
    Console.WriteLine((true ? "" : "not")); // <= Will out an empty
    // if r3.IsSquare() return false
    Console.WriteLine((false ? "" : "not")); // will out the word `not`

    Console.ReadKey();

Take a look MSDN

Simple example

int input = Convert.ToInt32(Console.ReadLine());
string classify;

// if-else construction.
if (input > 0)
    classify = "positive";
else
    classify = "negative";

// ?: conditional operator.
classify = (input > 0) ? "positive" : "negative";

It's a ternary operator. The basic way it works is like this:

bool thingToCheck = true;
var x = thingToCheck ? "thingToCheck is true" : "thingToCheck is false";
Console.WriteLine(x);

MSDN reference

As others have said, ? is a ternary operator.

So to answer the actual question,

Console.WriteLine("The rectangle with edges [{0},{1}] is {2}a square" ,
                r3.Edge1, r3.Edge2, (r3.IsSquare()) ? "" : "not ");

{0} and {1} will be replaced with the values of r3.Edge1 and r3.Edge2, respectively, when that line is written to the console. r3.IsSquare() is likely returning a boolean, so if it returns true, it'll write nothing (empty string "") but if it returns false, it'll write "not ".

So for example, the final result, assuming r3.IsSquare() returns false, would look like The rectangle with edges[3, 6] is not a square , if it had returned true, then it would say The rectangle with edges[3, 6] is a square .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM