简体   繁体   中英

What's the best practice for working with nullable SQL data in C#?

I tend to do this, for example a method that accepts an integer:

DoSomethingWithThisInt((int)dbObj.nullableInteger);

However I will also usually ensure that this code will never happen unless it has a value, sometimes this means I have to check for null first which takes more lines of code.

Is there a better way or am I doing this right by simply casting?

If you've already checked for null prior to the line of code in question, you can simply use

dbObj.nullableInteger.Value

As opposed to a cast.

If, for example, default values would also be sufficient (such as 0 for integers, false for booleans, etc.), then you can omit the null check and simply utilize

doObj.nullableInteger.GetValueOrDefault()

Basically there are two choices for syntax. Either use the properties of the Nullable<T> type, like so:

if (dbObj.nullableInteger.HasValue)
{
    DoSomethingWithThisInt(dbObj.nullableInteger.Value);
}

or use the syntactic sugar provided by the C# language, which translates to the same thing:

if (dbObj.nullableInteger != null)
{
    DoSomethingWithThisInt((int)dbObj.nullableInteger);
}

Which one you use is just a matter of preference; personally I prefer the latter.

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