1

The code below with the static keyword works fine but I want to make the below property as constant in C#.

The reason for doing so is the consistency through out the project. All the property which value is never going to change is marked as const not the static or static readonly in the existing project.

public class StatusList { public static Dictionary<DownloadStatus, int> DownlodStatusList { get { return new Dictionary<DownloadStatus, int>() { { DownloadStatus.Preview, (int)DownloadStatus.Preview }, { DownloadStatus.Active, (int)DownloadStatus.Active }, { DownloadStatus.Expired, (int)DownloadStatus.Expired }, { DownloadStatus.Inactive, (int)DownloadStatus.Inactive } }; } } } 
5
  • 3
    const value must be literal Commented Apr 1, 2019 at 11:48
  • You can mark property as static which will be same in nature as const Commented Apr 1, 2019 at 11:49
  • 2
    you can´t use new ... with const. That´s it. Commented Apr 1, 2019 at 11:49
  • Sorry @haim770 I have edited my code. Commented Apr 1, 2019 at 11:50
  • you can't but you could use readonly to achieve that (kind of) Commented Apr 1, 2019 at 12:00

2 Answers 2

1

You can't.

There's a difference between static readonly and const, in that whenever code references a const, the value of the const is baked directly into the point where it's referenced. Therefore a const can only be number, boolean, string, or null.

Sign up to request clarification or add additional context in comments.

Comments

0

From the docs:

Constants can be numbers, Boolean values, strings, or a null reference.

...

The initializer of a constant local or a constant field must be a constant expression that can be implicitly converted to the target type. A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and a null reference.

Having said this you can´t use const for anything that is not a compile-time literal. This in particular includes everything that was initialized with new.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.