Nullable types

Olli Aalto oaalto at gmail.com
Mon Oct 20 05:43:15 PDT 2008


Lionello Lunesu wrote:
> samabeau wrote:
>> Lionello Lunesu Wrote:
>>  
>>> * Are there any other languages with this concept?
>>
>> C# does. Nullable types have a question mark after them.
>> eg:-
>>
>> int? num = null;
>>
>> http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx
>>
> 
> In C#, that "?" basically wraps (boxes?) a value type into a reference 
> type.
> 
> Once you have an object reference (either an instanced class or such a 
> wrapped value type) you still must check for null everywhere you use it. 
> And in some situations you just know it's never null and you would like 
> to use that information.
> 
> At the moment, the way you can tell that an object is never null is by
> (1) using an assertion;
> (2) mentioning it in a comment;
> (3) using some hungarian-like naming scheme;
> 
> None of which have any value at compile-time. In fact, if you think 
> those 3 alternatives are good enough, you could drop all the 
> compile-time type checking.
> 
> And what happens nowadays when none of those 3 is present? You check for 
> null, whether the check makes sense or not. If I'd only get a penny for 
> every if-null check I've encountered...
> 
> Letting the type system track whether a reference is null or not should 
> result in more readable code. No more wondering "What if x is null? 
> Where's it checked?" and no more "let's check for null, just in case."
> 

In Objective-C you can call methods on null(nil in Obj-C) objects. The 
call is silently ignored. So no more crashes or NPEs.

The problem with this is that if you call a method on a null object and 
try to use the return value as an initializer for a local variable, it 
will be set to 0 for numbers, nil for objects, and so on. This can lead 
to hard to find bugs.

I'm not an expert Objective-C programmer, not even close, so I cannot 
say if this system is preferable to crashing the whole application.

O.







More information about the Digitalmars-d mailing list