How to declare a local constant in C#?

2019-02-21 09:40发布

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.

7条回答
SAY GOODBYE
2楼-- · 2019-02-21 09:54

As of 2018-10-02, it isn't possible to have a readonly local in c#, but there is an open proposal for that feature that has ongoing discussion.

This article provides a useful summary.

查看更多
够拽才男人
3楼-- · 2019-02-21 10:01

There is a sort of workaround that requires ReSharper. You can't get readonly locals, but you can at least detect mutated ones and color them differently.

Use the Fonts and Colors item Resharper Mutable Local Variable Identifier.

For me, I have locals colored grey, and then I chose a bold white for the mutated variables (this is with a dark theme). This means that any variable that is written to more than once shows up bright compared to regular ones. You can then do what you can to try to avoid having a mutated variable, or if the method really does require one then it will at least be highlighted.

查看更多
老娘就宠你
4楼-- · 2019-02-21 10:04

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'"
  }
}
查看更多
甜甜的少女心
5楼-- · 2019-02-21 10:07

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.

查看更多
做个烂人
6楼-- · 2019-02-21 10:10

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.

查看更多
可以哭但决不认输i
7楼-- · 2019-02-21 10:11

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.

查看更多
登录 后发表回答