C# interview
Denis Koroskin
2korden at gmail.com
Thu Oct 2 05:00:19 PDT 2008
On Thu, 02 Oct 2008 05:03:40 +0400, bearophile <bearophileHUGS at lycos.com>
wrote:
> Interview to Anders Hejlsberg, one C# author:
> http://www.computerworld.com.au/index.php/id;1149786074;fp;;fpid;;pf;1
>
> This is one of the questions:
>> Would you do anything differently in developing C# if you had the
>> chance?<
>
> This part of the answer shows a future feature of D (note that Delight
> already has this):
>
>> 50% of the bugs that people run into today, coding with C# in our
>> platform, and the same is true of Java for that matter, are probably
>> null reference exceptions. If we had had a stronger type system that
>> would allow you to say that 'this parameter may never be null, and you
>> compiler please check that at every call, by doing static analysis of
>> the code'. Then we could have stamped out classes of bugs.
>
>
It is a *very* good feature to have! I understand this as follows:
No class reference can have a null value, i.e. you can't write like this:
Object o;
o = new Object();
because o will store a null reference for a short time.
This is not valid, too:
Object o = new Object();
o = null;
This, however, is ok:
Object? o = null;
Object o2 = o; // ok, but throws an exception if o is null
void foo(Object? bar);
foo(null); // ok
void bar(Object baz);
bar(null); // compile-time error
Object o = ...;
bar(o); // always fine (because o can't be null)
However, T? needs language support. But once opImplicitCast will be
implement it won't need language support anymore:
struct Nullable(T) // called Likely in "The Power of None" by Andrei
Alexandrescu (http://www.nwcpp.org/Downloads/2006/The_Power_of_None.ppt)
{
private void* ptr;
this(T ptr)
{
this.ptr = ptr;
}
T opImplicitCast()
{
if (ptr is null) throw new NullReferenceException();
return cast(T)ptr;
}
}
T? is still nicier than Nullable!(T) to type. T?, however, might be a
syntactic sugar for Nullable template.
It can be further extended so that no T type would have T.init property:
int i1; // can't leave uninitialized
int? i2; // ok, initialized to null
int t1 = i1; // safe
int t2 = i2; // throws if i2 is null
int? find(T needle); // returns null if object is not found. Compare to
returning 0 or -1 or InvalidIndex or std::string::npos etc.
More information about the Digitalmars-d
mailing list