C# interview

Michel Fortin michel.fortin at michelf.com
Mon Oct 6 04:34:02 PDT 2008


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.

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?

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list