C# interview

Don nospam at nospam.com.au
Tue Oct 7 02:33:16 PDT 2008


Denis Koroskin wrote:
> On Mon, 06 Oct 2008 13:58:39 +0400, Don <nospam at nospam.com.au> wrote:
> 
>> Denis Koroskin wrote:
>>> The two things that needs to be changed to support this feature are:
>>>  1) make typeof(null) == void*
>>> 2) remove default initializers (for reference types, at least)
>>>  The latter rule can be relaxed (as done in C#): you can have a 
>>> variable uninitialized. However, you can't read from it until you 
>>> initialize it explicitly. This is enforced statically:
>>>  // The following is ok:
>>> Object o;
>>> o = new Object();
>>>  // This one is ok, too:
>>> Object o;
>>> if (condition) {
>>>    o = new Foo();
>>> } else {
>>>    o = new Bar();
>>> }
>>>  // But this is rejected:
>>> Object o;
>>> if (condition) {
>>>    o = new Foo();
>>> }
>>>  Object o2 = o; // use of (possibly) uninitialized variable
>>
>> Why not just disallow uninitialized references?
>> So none of the examples would compile, unless you wrote:
>>
>> Object o = new Object();
>>
>> or
>>
>> Object o = null;
>>
>> The statement that "50% of all bugs are of this type" is consistent 
>> with my experience. This wouldn't get all of them, but I reckon it'd 
>> catch most of them.
>> I can't see any advantage from omitting the "=null;"
> 
> That's the whole point - you won't need to check for (o is null) ever. 
> All the references are always valid. This might be a good contract to 
> enforce.

I think you misunderstood me. I wrote "=null" not "==null".
It's my experience that most null pointer bugs in D are caused by simply 
forgetting to initialize the reference. Anyone coming from C++ is 
extremely likely to do this. This bug could be completely eliminated by 
requiring objects to be initialized. If you want them to be be 
uninitialised, fine, set them equal to null. Make your intentions clear.

Then, an object reference could only ever be null if it was explicitly 
set to null.

There are some null pointer exceptions which are caused by returning a 
null by accident, but they're much rarer, and they're not much different 
to any other logic error. Yes, they would be eliminated in your 
proposal. But the cost-benefit is not nearly as good as eliminating the 
default null initialisation; the benefit is higher, but the cost is 
hundreds of times higher.




More information about the Digitalmars-d mailing list