A reference to the special NULL object is not the same thing as the
zero-pointer, which refers nothing (zero address is invalid).
Frankly, I don't see how it's all that different at all. There are some
minor semantic differences, but for all intents and purposes a "null" in
C# is pretty much the same as a "null" in C++.
That is why I
point out that pointer argument itself is allowed to be zero while
reference
is not. A reference must always refer something (whether a valid object
or
'null' object).
You can't use a null for a reference parameter in C++ either. The
following generates a compile error, just as the "ref" parameter example
you gave for C# does:
void Func(int &i)
{
}
void Caller()
{
Func(nullptr);
}
Thanks for the hint. I suppose it is the supposed way to do it in C#. It
has
two disadvantages though: 1) you must declare a bogus reference variable;
and 2) initialize it before passing to the function, where you could just
pass a 0 right away. Furthermore, it prevents you from using 'out'
arguments.
Again, how is this difference from passing by reference in C++?
Actually, pointers are needed to write directly to the address they
points
to.
In C#, a reference is needed to write directly to the address it points
to. Same thing.
Using reference to the bogus null-object, which we leave unmodifed when
assign a new value to the reference to return.
I don't understand this statement. How can you leave something unmodified
while at the same time assigning a new value?
This makes passing the bogus
value by reference a bit nonsenes. Pointers reach the same effect without
creating any bogus objects, which as stated above has additional usage
advantages.
The only real difference I see is that if you pass a pointer to a
_pointer_ in C++, that allows you to have similar behavior to (but not
exactly the same as) passing by reference, while at the same time allowing
for the parameter to be optional. For example:
void Func(int *pi)
{
if (pi != null)
{
*pi = <some result goes here>;
}
}
void Caller()
{
int i;
Func(&i);
Func(null);
}
However, I fail to see how this is really much of an advantage. In C# you
would be required to create a dummy local that you would just ignore. In
C++ you have to have code in the function itself to check whether the
parameter is null. Either way, there's extra code, and in the C# case it
eliminates the chance of a null-dereference run-time error (in C++, if you
forget to check for the parameter being null, you can crash).
I see this as _better_, not worse.
Peahaps, too much words for the issue. Yet, I do not know any places
where
it is discussed.
Frankly, after having seen several of these "rants" from you, I am left
wondering why you bother to use C#. I don't really think you understand
the issues you're talking about anyway, but even assuming you do, it seems
to me that if you feel C++ is so much better suited to your needs, then
that's the language you ought to be using.
Pete