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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With