We'll start with a really simple example - reference types:
string myOtherString = myString ?? "Something Else";
Console. WriteLine (myOtherString );
//Output: "Something Else"
Here we can see a string being assigned to null. Next we use the ?? operator to assign a value to myOtherString. Since myString is null, the ?? operator assigns the value "Something Else" to the string.
Let's get a little more complicated and see an example using nullable types.
int anotherInt = myInt ?? 1234;
Console. WriteLine (anotherInt. ToString ( ) );
//Output: "1234"
The ?? operator is a great way to assign a nullable type to a non-nullable type. If you were to attempt to assign myInt to anotherInt, you'd receive a compile error. You could cast myInt to an integer, but if it was null, you'd receive a runtime exception.
Granted, you can do the exact same thing with the regular conditional operator:
int anotherInt = myInt. HasValue ? myInt. Value : 1234;
Console. WriteLine (anotherInt. ToString ( ) );
//Output: "1234"
But, hey, that's a whole 22 extra characters - and really, it does add up when you are doing a lot of conversions from nullable to non-nullable types.
If you'd like to learn more about C# operators, I'd recommend checking out our two-parter series on operator overloading (part1, part2).
copyed from (http://blog.paranoidferret.com/index.php/2008/09/23/csharp-snippet-tutorial-the-double-questionmark-operator/)
本文介绍了C#中??运算符的基本用法及其在处理null值时的优势。通过两个示例,展示了如何使用??运算符为null类型的字符串和整数赋默认值,以及与条件运算符相比的简洁性。
455

被折叠的 条评论
为什么被折叠?



