Skip to main content
The 2026 Annual Developer Survey is live— take the Survey today!

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Const function parameter in C# [duplicate]

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.

Answer*

Draft saved
Draft discarded

Required fields are marked with *

Cancel
4
  • 2
    in C# now new you can use in keyword to pass value type as constant Commented Mar 20, 2020 at 7:12
  • @divyang4481 I had a quick look at the docs and couldn't see any examples of what you mean, can you post something? Commented Mar 20, 2020 at 7:56
  • please refer this link learn.microsoft.com/en-us/dotnet/csharp/language-reference/… Commented Mar 20, 2020 at 8:28
  • Cannot believe that the answer that suggests ref which let change the value is accepted and has highest number of bids so quickly adding quotation from official C# documentation: - in - specifies that this parameter is passed by reference but is only read by the called method. - ref - specifies that this parameter is passed by reference and may be read or written by the called method. - out - specifies that this parameter is passed by reference and is written by the called method. Commented Sep 15, 2020 at 22:57

lang-cs