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?
-
Yes, that is correct.
-
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).
-
myShortwill benullif the business object returnsnull.You can't reference
myShortas a value type directly, so this is OK.You can use
myShort.HasValueto see ifmyShortisnullor not.Use
myShort.Valueto 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 isnull. -
myShort will only be null if
UserBlahis implicitly convertible toNullable<Int16>and it is set to null, in which case it will not break unless you try to access a member ofmyShort.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 valueiik : GetValueOrDefault()Chris Doggett : 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.Konrad Rudolph : Use the null coalesce operator instead of the above pattern. -
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.
0 comments:
Post a Comment