How to declare a local constant in C# ?
Like in Java, you can do the following :
public void f(){ final int n = getNum(); // n declared constant }
How to do the same in C# ? I tried with readonly
and const
but none seems to work.
Any help would be greatly appreciated.
Thanks.
The const keyword Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.
The const keyword is used to modify a declaration of a field or local variable.
You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.
Local Variable: A local variable is a type of variable that we declare inside a block or a function, unlike the global variable. Thus, we also have to declare a local variable in c at the beginning of a given block. Example, void function1(){ int x=10; // a local variable.
In C#, you cannot create a constant that is retrieved from a method.
Edit: dead link http://msdn.microsoft.com/en-us/library/e6w8fe1b(VS.71).aspx
This doc should help: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/const
A constant expression is an expression that can be fully evaluated at compile time.
Declare your local variable as an iteration variable. Iteration variables are readonly (You didn't ask for a pretty solution).
public void f() { foreach (int n in new int[] { getNum() }) // n declared constant { n = 3; // won't compile: "error CS1656: Cannot assign to 'n' because it is a 'foreach iteration variable'" } }
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