I've known about these beauties for quite some time, but never thought of sharing them until now. They're a bit obscure, and I want to help remedy that.
=============== =============== =============== ==========
?? is a C# binary operator used to provide a default value should the left operand be null. For example:
equates to:
Relatively simple, but a great time saver, and sometimes quite useful. Another example:
In this example, if TextBox1 is not null, result will contain TextBox1.Text. Otherwise, it will contain a blank string, since that is what new TextBoxes are initialized to.
=============== =============== =============== ==========
?: is a C# (and many other languages) ternary operator used to return a value based on the evaluation of a boolean expression. This one is far more commonly known than the ?? operator, because it has its roots in C, but I'm still surprised at how many people don't know how to use it. Here's an example of how it works:
This is equivalent to:
A more practical example:
This code sets substr's value to the first 10 characters of fullstr, unless fullstr is shorter than 10 characters, in which case, substr is assigned the value of fullstr.
=============== =============== =============== ==========
Hope you found this enlightening!
=============== =============== =============== ==========
?? is a C# binary operator used to provide a default value should the left operand be null. For example:
Code:
X = A ?? B;
Code:
if(A != null) X = A; else X = B;
Code:
string result = ( TextBox1 ?? new TextBox() ).Text;
=============== =============== =============== ==========
?: is a C# (and many other languages) ternary operator used to return a value based on the evaluation of a boolean expression. This one is far more commonly known than the ?? operator, because it has its roots in C, but I'm still surprised at how many people don't know how to use it. Here's an example of how it works:
Code:
X = A ? B : C;
Code:
if(A) X = B; else X = C;
Code:
string substr = fullstr.Length > 10 ? fullstr.Substring(0, 10) : fullstr;
=============== =============== =============== ==========
Hope you found this enlightening!
Comment