tags:

views:

140

answers:

8

A business object is returning a short? datatype.

How would I get this value into a variable?

short? myShort = SomeBusinessObject.UserBlah;

Is that correct? Will it break if it is null?

+1  A: 

Yes, that is correct.

Michael Kniskern
+2  A: 

Are you actually trying to protect against SomeBusinessObject being null? If so, nullable types won't help you there. You still need to check whether your SomeBusinessObject is null.

I'm assuming that this is the case because if UserBlah returns a short then it'll never be null (as short is not a nullable type).

Martin Peck
+1  A: 

myShort will be null if the business object returns null.

You can't reference myShort as a value type directly, so this is OK.

You can use myShort.HasValue to see if myShort is null or not.

Use myShort.Value to get the value. It will throw an exception if no value is defined.

You can use GetValueOrDefault() and pass in a default to get a value even if none is defined (null). This function returns the value you passed in if the nullable type is null.

Josh G
+1  A: 

myShort will only be null if UserBlah is implicitly convertible to Nullable<Int16> and it is set to null, in which case it will not break unless you try to access a member of myShort.Value.

You can also do this:

short defaultValue = 0;
short myShort      = SomeBusinessObject.UserBlah ?? defaultValue;
Mark Cidade
+4  A: 

That's correct. You only have to worry if you're assigning myShort to a non-nullable short, in which case you have to check HasValue, like so:

short s = myShort.HasValue ? myShort.Value : (short) 0; // or some other short value
Chris Doggett
GetValueOrDefault()
iik
Even better. I use this syntax because the default is 0, and we use *.MinValue if the DB value is null. We're still transitioning to nullable types with a legacy system.
Chris Doggett
Use the null coalesce operator instead of the above pattern.
Konrad Rudolph
+4  A: 

To get it into a variable use myShort.Value after checking myShort.HasValue

Arnshea
+2  A: 

Don't forget about the null coalescing operator.

short myShort = SomeBusinessObject.UserBlah ?? 0;

if SomeBusinessObject.UserBlah is null, it just passes the value to the right of ?? so you can default it to something.

Joshua Belden