J
JJ Feminella
This statement is legal C#:
public const string day = "Sunday";
but this statement is not:
public const string[] days = new string[] { "Sun", "Mon", "Tue" };
The C# Programmer's Reference specifies that 'the only valid values of a constant declarator [involve] constant expressions'. A constant expression is defined as 'an expression that can be fully evaluated at compile-time ... Therefore, the only possible values for constants of reference types are string and null.'
In other words, constant arrays of any otherwise constant type are not legal C#. I understand that this is the case because string[] is really of type System.Array, which is an object (also a dead giveaway since we used the new operator). Fine. I'll get the next best thing and use static readonly in place of where I'd like to use const. The statement becomes:
public static readonly string[] days = new string[] { "Sun", "Mon", "Tue" };
and the compiler's happy.
But now if I run FxCop on an assembly containing this statement, it gets mad at me:
'... Fields that are arrays should not be readonly'
'Make the array 'const' to truly protect its contents.'
What the heck? Am I missing something here? How do you declare a constant array? Any help would be greatly appreciated. Thanks.
public const string day = "Sunday";
but this statement is not:
public const string[] days = new string[] { "Sun", "Mon", "Tue" };
The C# Programmer's Reference specifies that 'the only valid values of a constant declarator [involve] constant expressions'. A constant expression is defined as 'an expression that can be fully evaluated at compile-time ... Therefore, the only possible values for constants of reference types are string and null.'
In other words, constant arrays of any otherwise constant type are not legal C#. I understand that this is the case because string[] is really of type System.Array, which is an object (also a dead giveaway since we used the new operator). Fine. I'll get the next best thing and use static readonly in place of where I'd like to use const. The statement becomes:
public static readonly string[] days = new string[] { "Sun", "Mon", "Tue" };
and the compiler's happy.
But now if I run FxCop on an assembly containing this statement, it gets mad at me:
'... Fields that are arrays should not be readonly'
'Make the array 'const' to truly protect its contents.'
What the heck? Am I missing something here? How do you declare a constant array? Any help would be greatly appreciated. Thanks.