Possible Duplicate:
Read-only (“const”-like) function parameters of C#
Why is there no const member method in C# and const parameter?
Having programmed in C++ in the past, I recall we could make a constant reference/pointer parameter in a method.
If my memory is correct, the below means, that the method cannot alter the reference and the reference itself is a constant reference.
void DisplayData(const string &value) const
{
std::count << value << endl;
}
Is there an equivalent in C# for methods in a class?
The reason why I'm asking is, I'm trying to pass a object by reference (for speed) and at the same time don't want anyone to alter it.
Update 16/09/2020
There now appears to be the in
parameter modifier that exhibits this behaviour (in essence, a ref readonly
). A brief search on when you would ever use this yields the following answer:
Why would one ever use the "in" parameter modifier in C#?
Original Answer
There is no equivalent for C# and it has been asked many, many, many, many times before.
If you don't want anyone to alter the "reference", or perhaps you mean the content of the object, make sure the class doesn't expose any public setters or methods of mutating the class. If you cannot change the class, have it implement an interface that only publicly exposes the members in a read-only fashion and pass the interface reference instead.
If you mean you want to stop the method from changing the reference, then by default if you pass it "by reference", you are actually passing the reference by value. Any attempt from the method to change what the reference points to will only affect the local method copy, not the caller's copy. This can be changed by using the ref
keyword on a reference type, at which point the method can point the reference at a new underlying object and it will affect the caller.
For value types (int
, double
, byte
, char
,...,struct
) the arguments come in as values and therefore are guaranteed not to affect that calling module.
For string
type, although it is a reference type, it is immutable by the CLR, such that nothing you do inside the procedure can affect the original string.
For other reference types (class
) there is no way to guarantee changes in the class from the method.
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