C# Snippet Tutorial - The ?? Operator

We'll start with a really simple example - reference types:

string myString = null;

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? myInt = null;

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? myInt = null;

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/)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值