When you use say
int? i = null;
what you are really saying is
Nullable<int> i = null;
Now Nullable<T> is a value type generic. It contains the value (in this case an int) and a boolean flag to state whether the value has been set or not. So in terms of overhead you are simply adding a boolean flag to the structure.
As far as compatibility to teh non-nullable types, you can write
int? i = 5;
if( i.HasValue )
{
int j = (int)i;
int k = i.Value;
}
both of these constructs work. However, if you do not perform the check first and simply try to cast or assign the Value - and the nullable type is null - then you will get an InvalidOperationException
Regards
Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog http://www.dotnetconsult.co.uk
I was just looking at an article about using nullable value types. (value
types that can effectively have no value and not be set).
The syntax is to append a question-mark to the value type in the
declaration, eg:
int? age;
I don't like that much, I think it would be much more consistent to use a
new keyword, such as "nullable". But anyways...
A couple of questions for anyone who actually has the beta installed:
1. What's the overhead of declaring your value types nullable?
2. Are they type-compatible with non-nullable value types? (ie. can I assign
one to the other?).
Thanks,
John