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?
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?
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).
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
.
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;
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
To get it into a variable use myShort.Value after checking myShort.HasValue
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.