C# interview

Denis Koroskin 2korden at gmail.com
Mon Oct 6 03:13:38 PDT 2008


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.

string foo(Bar o)
{
     // should we check for null or not?
     return o.toString();
}

Bar getBar()
{
     if (...) {
         return new Bar();
     } else {
         // should we throw an exception or return null?
         return null;
     }
}

// should we check for null here?
string str = foo( getBar() );

Too much choices. The better code would be as follows:

string foo(Bar o)
{
     // no checking needed here, o can't be null!
     return o.toString();
}

Bar? getBar()
{
     if (...) {
         return new Bar();
     } else {
         // ok, we can return null and user *knows* about that!
         // this is very important
         return null;
     }
}

string str = foo( getBar() ); // might throw a NullReference exception  
(just what we need!)

alternatively you can make checking yourself:

Bar? bar = getBar();
string str = (bar is null) ? "underfined" : foo(bar); // ok, it's safe

Please, comment!



More information about the Digitalmars-d mailing list