views:

416

answers:

5

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.

+5  A: 

I'm not sure why readonly and const didn't work for you since these are the keywords you need. You use const if you have a literal (except for array literals) and readonly otherwise:

public void f()
{
    const int answer = 42;
}

private readonly int[] array = new int[] { 1, 2, 3, 4 };
private readonly DateTime date = DateTime.Now;
public void g()
{
    Console.WriteLine(date.ToString());   
}

readonly only works on class level (that is, you can only apply it to fields). Also as a consequence of const requiring a literal, it's inherently static while a readonly field can be either static or instance.

DrJokepu
It's important to note that creating a readonly instance of a reference type only means that the reference itself can't be changed; the object can still be modified normally (unless the type is immutable, like String).
CodeSavvyGeek
The answer to **your** question is simple -- none of them (const, readonly) would work in a given example.
macias
+1  A: 

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

From MSDN.

Since C# can't enforce "const correctnes" (like c++) anyway, I don't think it's very useful. Since functions are very narrwoly scoped, it is easy not to lose oversight.

Johannes Rudolph
I must point out however, that eric dahlvang is still right about why const didn't work in your case.
Johannes Rudolph
"Since functions are very narrwoly scoped, it is easy not to lose oversight." - Why do other languages like C++ and Java provide such mechanism then?
missingfaktor
Don't know about java, but c++ can enforce true const also on references, what c# can't. I have never seen const used locally anywhere else than in c++.
Johannes Rudolph
A: 

Have a look at the MSDN Documentation about C# constants

Rowno
+7  A: 

In C#, you cannot create a constant that is retrieved from a method.

http://msdn.microsoft.com/en-us/library/e6w8fe1b(VS.71).aspx

Eric Dahlvang
+2  A: 

In the example you gave, you need to declare the variable as static, because you're initializing it with a method call. If you were initializing with a constant value, like 42, you can use const. For classes, structs and arrays, readonly should work.

Neil T.
Please note that you cannot use static on variables, only on members.
DrJokepu