Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const function parameter in C# [duplicate]

Tags:

c#

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.

C++ example

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.

like image 375
TheLazyChap Avatar asked Jun 11 '12 14:06

TheLazyChap


2 Answers

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.

like image 145
Adam Houldsworth Avatar answered Oct 09 '22 18:10

Adam Houldsworth


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.

like image 20
John Alexiou Avatar answered Oct 09 '22 18:10

John Alexiou