Receiving 'Expression being assigned must be constant' when it is
Is there a way to use something like this:
private const int MaxTextLength = "Text i want to use".Length;
I think it would be more readable开发者_开发知识库 and less error prone than using something like:
private const int MaxTextLength = 18;
Are there any ways to have the length of the text be the source for a constant variable?
private readonly static int MaxTextLength = "Text i want to use".Length;
Use static readonly
instead of const
.
Constants have to be compile time constants
Unfortunately, if you are using the const keyword the value on the right side of the '=' must be a compile-time constant. Using a "string".length requires .NET code to execute which can only occur when the application is running, not during compile time.
You can consider making the field readonly rather than a const.
Does the value need to be a const? Would a static readonly work for your case?
private static readonly int MaxTextLength = "Text i want to use".Length;
This will allow you to write the code in a similar manner to your first example.
Not sure why you want to do this but how about...
private const string MaxText = "Text i want to use.";
private static int MaxTextLength { get { return MaxText.Length; } }
精彩评论