Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a local constant in C#?

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.

like image 911
missingfaktor Avatar asked Jan 13 '10 05:01

missingfaktor


People also ask

How do you declare constants in C?

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.

How can we declare a local variable as constant?

The const keyword is used to modify a declaration of a field or local variable.

How do you declare a constant?

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.

What is local variable declaration in C?

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.


2 Answers

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.

like image 146
Eric Dahlvang Avatar answered Sep 29 '22 16:09

Eric Dahlvang


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'"   } } 
like image 34
ZunTzu Avatar answered Sep 29 '22 16:09

ZunTzu