This might be a duplicate question.But could not find it in search In java to mark a method parameter as constant we declare it as final whats the equivalent C# keyword? Like
public void doSomeThing(final object myObject)
{
//print myobject
}
This might be a duplicate question.But could not find it in search In java to mark a method parameter as constant we declare it as final whats the equivalent C# keyword? Like
public void doSomeThing(final object myObject)
{
//print myobject
}
This is not possible in C# - there is no way to mark a passed in parameter as a constant.
If you have a const
that needs to be available to many functions, why not declare it with the right scoping (class scoping or global if needed)?
C# has a readonly keyword but it cannot be uset to local variables (class members only). This means that there is no way to mark a metheod parameter constant.
I miss it too cause in my Java code almost every parameter and local variable is final (which is a good coding pattern I believe).
There is a readonly
keyword in C# but so far we can only apply it to fields, not locals or parameters.
Often in Java the final
keyword is used habitually as a matter of style, to make it easier to close over values in anonymous inner classes. But that problem doesn't exist in C# as anonymous methods/lambdas can close over modifiable variables.
Also tools like Resharper can display mutated variables/parameters in a different colour, so you can see the "complications" in your method at a glance. I use it to make mutated names light up in bold green text or something like that!
This is not to say that C# itself wouldn't be improved by many more features like a widely applicable readonly
to help with declared immutability. But if you have short methods and Resharper to highlight things for you, then you don't entirely need to manually declare things as final/readonly/const (depending on the language). The IDE tracks it for you.
This makes more sense: as Java coders have discovered, most "variables" are not variables at all. But if you have to declare this by adding final
to everything, that's a lot of extra keyword noise in your code. It would make more sense for the default to be final
and to have a keyword to make things mutable
. This is how it works in F#.
In C# 4.0 / Visual Studio 2010 with the Code Contracts add-on installed you can use Contract.Invariant in a ContractInvariantMethod attribute to check that a value is not modified during a method call.
Not quite the same thing but about as close as you'll get I think.
As others stated, there's no such thing in C#.
If your intention is to forbid the called method to change your object (or know for sure it does not), your only option is to pass a deep clone of your object. - Not very elegant, but the only way possible to be sure.