
Originally Posted by
Znurre
Of course I know this, but I was referring to the syntax.
In C# you never choose whetver you want to pass something by reference or value, correct me if I am wrong but the ref "operator" seems to be only for decoration.
Actually, that's incorrect:
Code:
class Test
{
void Foo(int i) { i = 5; }
void Bar(ref int i) { i = 10; }
public static void Main()
{
int i = 0;
Foo(i);
Console.WriteLine(i);
Bar(ref i);
Console.WriteLine(i);
}
}
The reason for the confusion is that in C# (like in Java) class are reference types (C#, unlike Java, also provides value types, i.e. structs), so you can pass a reference type by value (default) or by reference (ref/out keywords). There is a subtle - but important! - distinction between the two: in the first case, if you assign null to the parameter inside the function, this won't be reflected outside the function; in the second case, the change will affect the parameter outside the function, too. (The same thing would happen if you assigned a new instance).
At least I really like the strict syntax of C++ with pointers, references etc.
I feel that C++ references leave a lot to be desired. They cannot be reseated (i.e. once you assign a reference to a variable, it is an error to reassign that variable), they cannot be stored in vectors or standard containers (due to the above) and they are silent and deadly. For instance this:
what's the value of i after the call? In C++ you cannot know, leading to hard-to-find bugs. In C# you know it will be 0.
At least with pointers, you have the distinction between Foo(i) and Foo(&i), telling you everything you need to know at a glance.
In short, C# is better-design than C++, simply because it takes the experience we gained with C++ (and Java, Delphi and various) and distills it into something with fewer pitfalls and corner-cases.