A G
A G

Reputation: 22587

? 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);

Upvotes: 2

Views: 362

Answers (6)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28718

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

Upvotes: 1

Jeff Mercado
Jeff Mercado

Reputation: 134871

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.

Upvotes: 2

Euphoric
Euphoric

Reputation: 12849

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.

Upvotes: 5

Jeff Hubbard
Jeff Hubbard

Reputation: 9892

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.

Upvotes: 0

Scott M.
Scott M.

Reputation: 7347

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.

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176896

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 - ??

Upvotes: 0

Related Questions