Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can a method parameter pass an object by reference but be read-only?

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#?

like image 255
CJ7 Avatar asked Aug 08 '10 08:08

CJ7


People also ask

What is the best way to declare a method parameter that behaves as a readonly reference variable?

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.

Does Java pass objects by reference?

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.

What is in parameter in C#?

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.

Is Java pass by value?

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.


1 Answers

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.

like image 162
Matthew Flaschen Avatar answered Oct 12 '22 01:10

Matthew Flaschen