-2

I recently came across this bit of code:

 public void AppendTextColour(string text, Color color, bool AddNewLine = false)
        {
            rtbDisplay.SuspendLayout();
            rtbDisplay.SelectionColor = color;
            rtbDisplay.AppendText(AddNewLine
                ? $"{text}{Environment.NewLine}"
                : text);
            rtbDisplay.ScrollToCaret();
            rtbDisplay.ResumeLayout();
        }

What fascinates me about it is the restructuring of AppendText(); bit here:

rtbDisplay.AppendText(AddNewLine? $"{text}{Environment.NewLine}": text);

I can only guess that the question mark is used to instantiate the boolean value, however the dollar sign and the double dots sign here are absolutely obscure. Can anyone dissect this bit and explain it to me?

I apologise if I am being a bit ambiguous but I was unable to find any relevant information anywhere. :/

  • 4
    Check C# documentation for [ternary operator](https://stackoverflow.com/documentation/c%23/18/operators/6029/ternary-operator#t=201706210748539600617) and [interpolated strings](https://stackoverflow.com/documentation/c%23/24/c-sharp-6-0-features/49/string-interpolation#t=201706210748003145712) – Adriano Repetti Jun 21 '17 at 07:47
  • See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator for the *conditional operator*. (It's sometimes called the ternary operator, but its actual name is the conditional ?: operator) – Jon Skeet Jun 21 '17 at 07:49
  • 1
    By the way, whenever you're trying to find the name of a weird operator in a programming language, try searching for the **list of operators**. – cbr Jun 21 '17 at 07:49
  • BTW now that I posted a comment with **TWO** links to SO Documentation...I feel a better contributor. Hey Mr. SO, I want a T-Shirt! – Adriano Repetti Jun 21 '17 at 07:51

1 Answers1

0

This line:

rtbDisplay.AppendText(AddNewLine? $"{text}{Environment.NewLine}": text);

can be written as:

if (AddNewLine){
    rtbDisplay.AppendText(string.Format("{0}{1}",text, Environment.NewLine)); // or just (text + Environment.NewLine)
} else {
    rtbDisplay.AppendText(text);
}

It uses the ternary operator and string interpolation (introduced in C# 6)

Nasreddine
  • 36,610
  • 17
  • 75
  • 94