C# interview

Denis Koroskin 2korden at gmail.com
Mon Oct 6 06:11:41 PDT 2008


On Mon, 06 Oct 2008 15:34:02 +0400, Michel Fortin  
<michel.fortin at michelf.com> wrote:

> On 2008-10-06 06:13:38 -0400, "Denis Koroskin" <2korden at gmail.com> said:
>
>> 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!
>
> I like it.
>
> And I think it should extend to any pointer. But would this:
>
> 	char* a; // non-null pointer
>
> become this:
>
> 	char*? b; // "?" makes the pointer nullable
>
> or this:
>
> 	char? b; // "?" means nullable pointer
>
> ?
>
> "char?" doesn't seem to work since then for consistency "Object?" should  
> be a nullable pointer to an Object reference. But then, "char*?" isn't  
> very appealing.
>

No, these are different types:

char? <-> Nullable@(char)
char*? <-> Nullable@(char*)

This is for consistency. T? should be implicitly castable to T:

int? c; // c is uninitialized and stores null
assert(c is null);
// int x = c; // throws an "Uninitialized value used" exception

c = 42;
assert(c !is null);
int z = c; // ok because c is initialized

Another example:
// returns null on error
// compare to C atoi behaviour - returns 0 on error
int? atoi(string str);

> Oh, and does that mean we now have "const(Object)?" to create non-const  
> pointers to const objects? That'd be nice. :-)
>
> Perhaps "Object" should just be a shortcut for "Object*", which would  
> mean that you could write "const(Object)*" if you wanted, and "char?"  
> could work as a nullable pointer. But then, "==" wouldn't work right for  
> objects (because it'd have to compare pointers), am I right?
>




More information about the Digitalmars-d mailing list