简体   繁体   中英

? Operator VS ?? Operator Usage

The following statement works:

Class.ID = odrDataReader["ID"] == null ? 0 : Convert.ToInt32(odrDataReader["ID"]);

But the following does not:

Class.ID = odrDataReader["ID"] as int? ?? 0; //ID is always 0

Any one can explain why ?? operator always returns 0 even when ID column is not null?

Solution(suggested by Kirk):

Class.ID = Convert.ToInt32(odrDataReader["ID"] ?? 0);

In first one you use Convert.ToInt32(odrDataReader["ID"]) in second one you use odrDataReader["ID"] as int? . From what you say first one is correct, so you should use Convert in second too.

Actualy I think first is fine, because it would look weird if you really wanted to use ?? operator.

Edit : To explain a bit odrDataReader["ID"] as int? is NOT a conversion. It will always return null if odrDataReader["ID"] is string.

It all depends on the type of the ID column. If it was indeed of type int? , then you should be able to do this with no problems:

Class.ID = (int?)odrDataReader["ID"] ?? 0;

However it is more likely that this is not the case and is a different type (I'd guess string ). A string is clearly not a int? and thus odrDataReader["ID"] as int? always returns null and you get the value 0 . As Euphoric mentions, the as operator only does reference/boxing conversions. If this is the case, using ?? is not an option for you and you must use the first expression.

It's definitely because you are doing odrDataReader["ID"] as int? - that is the difference between the two statements, and using the as keyword is not the same as doing a Convert .

If you want to use ?? you could try

Class.ID = Convert.ToInt32(odrDataReader["ID"] ?? 0);

Misread the question. I'm guessing it's because you're casting odrDataReader["ID"] to int? before checking it. You should try skipping the cast, though I doubt that's what's really the problem.

Coalescing operator is new operator added in C#2.0. Coalescing operator is also known as ??.

Nullable<int> a = null;
Nullable<int> b = 10;
int c = a ?? b.Value;

Coalescing operator Coalescing operator work some what similar to ternary operator but it works only with the Nullable types only. so its sort hand operator to deal with Nullable types only.

check my blog post : Coalescing operator - ??

the ?? operator is the null-coalescing operator . It defines a default value if the value is found to be null. Int32 is a value type in .NET, which normally can't take a null value, so the int? designates an Int32 that can be null.

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