It's 3 am and i don't feel like sleeping. I've been helping a friend to work on his code and now i'm only partially tired. Well, why not continue with my series on the evolution of C#? Let's do it!
So, this time i'm going to talk about nullable types. Everybody used them already, but back in .Net 1.0 they didn't exist. How did you represent a "no value present" value? Sure, string can have null, but null is different than empty, right? How do you represent an empty numeric type then? You check if it is bigger than 0? Well for some cases that's just how developers did it. Either that or create a constant value that represents a "no value". But, to me, that is not expressive enough.
Basically, a nullable type is only a non-nullable type wrapped in the System.Nullable struct. This is a generic struct, so it makes use of the Generic features of C# 2.0. The struct is very simple, it contains only a HasValue and a Value property. Both are very explicit and this makes it easy to work with. As for the sintax, check this out:
The above two lines have the same meaning. You can assign null to both of the variables and use the same properties. It's just syntactic sugar!
In my opinion, nullable types bring the following benefits:
So, this time i'm going to talk about nullable types. Everybody used them already, but back in .Net 1.0 they didn't exist. How did you represent a "no value present" value? Sure, string can have null, but null is different than empty, right? How do you represent an empty numeric type then? You check if it is bigger than 0? Well for some cases that's just how developers did it. Either that or create a constant value that represents a "no value". But, to me, that is not expressive enough.
Basically, a nullable type is only a non-nullable type wrapped in the System.Nullable struct. This is a generic struct, so it makes use of the Generic features of C# 2.0. The struct is very simple, it contains only a HasValue and a Value property. Both are very explicit and this makes it easy to work with. As for the sintax, check this out:
The above two lines have the same meaning. You can assign null to both of the variables and use the same properties. It's just syntactic sugar!
In my opinion, nullable types bring the following benefits:
- They add simplicity when dealing with databases. In MS SQL Server, you can have a null int, numeric, or whatever you like.
- They can transmit the meaning of a parameter/variable more clearly. If that parameter is optional, just let it be nullable (although we have optional parameters too, now).
Note that you cant have nullable reference types (does it even make any sense?) nor nullable inside a nullable (double null?). This is a little feature that was not so noticed by some people i know and therefore is a little underused.
Thanks, till next time!
Comments
Post a Comment