Search code examples
c#constantsreadonlyparameter-passing

Can parameters be constant?


I'm looking for the C# equivalent of Java's final. Does it exist?

Does C# have anything like the following:

public Foo(final int bar);

In the above example, bar is a read only variable and cannot be changed by Foo(). Is there any way to do this in C#?

For instance, maybe I have a long method that will be working with x, y, and z coordinates of some object (ints). I want to be absolutely certain that the function doesn't alter these values in any way, thereby corrupting the data. Thus, I would like to declare them readonly.

public Foo(int x, int y, int z) {
     // do stuff
     x++; // oops. This corrupts the data. Can this be caught at compile time?
     // do more stuff, assuming x is still the original value.
}

Solution

  • Unfortunately you cannot do this in C#.

    The const keyword can only be used for local variables and fields.

    The readonly keyword can only be used on fields.

    NOTE: The Java language also supports having final parameters to a method. This functionality is non-existent in C#.

    from http://www.25hoursaday.com/CsharpVsJava.html

    EDIT (2019/08/13): I'm throwing this in for visibility since this is accepted and highest on the list. It's now kind of possible with in parameters. See the answer below this one for details.