C#: can you make it so that a method parameter passes an object by reference but is read-only?
eg:
void MyMethod(int x, int y, read-only MyObject obj)
where obj
is an object reference but this object cannot be modified during the method.
Can this be achieved in C#?
Declaring in parameters in parameters are declared by using in keyword as a modifier in the parameter signature. For all purposes the in parameter is treated as a readonly variable. Most of the restrictions on the use of in parameters inside the method are the same as with readonly fields.
We can think of Java intuitively as pass-by-reference for all objects. This is why we professors called Java pass-by-reference. Java is officially always pass-by-value.
The in keyword causes arguments to be passed by reference but ensures the argument is not modified. It makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument.
Java always passes parameter variables by value. Object variables in Java always point to the real object in the memory heap. A mutable object's value can be changed when it is passed to a method.
No. C# has no direct analogue to C++ const
(its own const is something different). A common C# pattern for this is to pass in a interface, such as IEnumerable
, that does not permit modifications. You can also create an immutable copy or wrapper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With