Reputation: 489
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?
Upvotes: 35
Views: 40890
Reputation: 1888
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.
Upvotes: 4
Reputation: 48415
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; } }
Upvotes: 0
Reputation: 6989
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.
Upvotes: 17
Reputation: 136613
Use static readonly
instead of const
.
Constants have to be compile time constants
Upvotes: 33
Reputation: 44605
private readonly static int MaxTextLength = "Text i want to use".Length;
Upvotes: 45