My question is related to C# function parameters. I’m used to C++ where parameters are values by default unless you explicitly specify them as references. So, in C#, how do I make function parameters to be passed by value instead of by reference? Actually, I just want to know how to pass a variable, and not have that variable modified after the call to the function.
E.g:
void foo(Widget w)
{
w.X = 3;//where w wouldn't really be modified here
}
As
intis a primitive data type,xis already passed by value in your older example.Proof of concept:
EDIT: for non-primitive data types, the answers to this question state that C# doesn’t implement copy constructors like C++ does, so I’m not sure of a way to pass actual objects by value, other than making your class implement the
ICloneableinterface or something. (For the record, C# passes references to objects by value.)EDIT 2: Mark Rushakoff’s answer is an excellent, if not the best, way to go… assuming your
Widgettype is defined by you (it looks so).