Domanda

I have a SQL Reader object over which I iterate, and as things usually go, you never quite know what you're going to get. Whatever value is returned by the reader needs to be cast as a double, but if it returns a null I need to gracefully handle it with a default value, which in this case is zero. I started out with code similar to this...

double x;
if (reader[1] is double)
    x = (double)reader[1];
else
    x = 0;

... which seemed to do the trick, but I wasn't satisfied. I figured that the mysterious team that designs C# would have an operator for this, and what do you know, there is. So, then I ended up with a slightly different implementation...

var x = reader[1] as Double? ?? 0;

I couldn't tell you if the two examples above are equivalent because like all newbs I take code that I think will do the trick and use it for important things - partial joke. What I do know is that I have yet for either implementation to throw an exception when hitting the database and getting a null result, and this leads me to believe that both work as I expect but I'd rather be sure.

So, on to my questions. Can someone explain what potential differences in functionality I could experience from using either? If possible, could someone provide/explain a better implementation of the second example? I find the null-coalesce operator pretty sexy but I don't really know if I'm implementing it in the best way. Thanks.

È stato utile?

Soluzione

If you already know the column position (ordinal) as it seems in your case, you are much better off using the correct data type retriever and check for null before hand like this

double x = reader.IsDBNull(1) ? 0 : reader.GetDouble(1);

Altri suggerimenti

Your two examples are functionally equivalent: null will resolve to 0, double will resolve to its value. For most practical purposes, they both run in no time. (if you actually need to know, the latter should run slightly faster) I prefer the latter (using null-coalescing) for readability.

However, note that if you might encounter other values, such as an int or string, you might want to consider using Convert.ToDouble, which will attempt to convert whatever value you give it. It will also default a null as 0.

the as keyword has an extra cost, because it is already casting the object into the wanted type.

Use var x = !reader.IsDBNull(1) ? r.GetDouble(1) : 0;

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top