
Originally Posted by
Ansla
So change it to use a non-static code if C# doesn't like it, the problem will still be there. Java passes parameters "as value", but what it actually passes as value is a reference, so you can make changes to the object using either of the references. As far as I know C# does the same thing, and I'm not aware of any way to pass the actual data as value in either of the languages, though my knowledge of VM based languages is limited so please correct if I'm wrong and you can replicate what the following C++ function does:
Code:
struct Message {
std::string text;
};
void PrintMessage(Message msg) {
std::cout << msg.text << std::endl;
}
Whatever the caller does, if msg.text contains "Hi" when the function is called that's what will appear on the screen. Unless the function itself changes msg.text, but that's no side effect, if a programmer did that and didn't expect the result it's time to look for another profession, no language can be that idiot proof.
Code:
struct Message {
public string Text;
}
void PrintMessage(Message msg) {
Console.WriteLine(msg.Text);
}
This is identical to the C++ version. The msg parameter in PrintMessage is pass-by-value, and Message is a struct (aka value type) which gets copied on the stack when passed as a parameter - exactly like the C++ version. Additionally, C# strings are immutable, which means they cannot be modified after creation. This code will always print "Hi", as expected:
Code:
volatile var msg = new Message { Text = "Hi" };
PrintMessage(msg);
var troll = new Thread(() => msg.Text = "Trolled");
troll.Start();
struct Message { public string Text; }
void PrintMessage(Message msg) { Thread.Sleep(5000); Console.WriteLine(msg.Text); }
However, do any of the following changes and it will print "Trolled":
Code:
class Message { public string Text; } // classes are reference types, like Java
or
Code:
void PrintMessage(ref Message msg) { ... } // use pass-by-reference
unsafe void PrintMessage(Message* msg) { ... } // use pass-by-value with pointer
The main differences between C++ and C# parameter-passing semantics is that C# classes are reference types by default (so no "slicing" issues to take care of) and that C# lacks pass-by-const-reference (which hurts its math performance significantly). Everything else is there, and this is a pretty significant advantage of C# over Java.