Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving 'Expression being assigned must be constant' when it is

Tags:

c#

.net

constants

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?

like image 870
michael Avatar asked Sep 08 '11 12:09

michael


4 Answers

private readonly static int MaxTextLength = "Text i want to use".Length;
like image 87
Davide Piras Avatar answered Nov 14 '22 19:11

Davide Piras


Use static readonly instead of const.

Constants have to be compile time constants

like image 23
Gishu Avatar answered Nov 14 '22 19:11

Gishu


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.

like image 17
Kevin Kalitowski Avatar answered Nov 14 '22 19:11

Kevin Kalitowski


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.

like image 2
jhamm Avatar answered Nov 14 '22 19:11

jhamm