0

I start learning C# couple of weeks ago and I can't figure out how to declare a public const char array.

This is what I have:

public static class MyClass { public const char[] MyCharArray= new char[]{'a','b','x','c'}; } 

The error is pretty clear, however I have not found a way to fix this:

'MyClass.MyCharArray' must be constant

It needs to be const because I need to use it as a argument for custom data annotation validation. Ex: [MyCustumValidation(MyClass.MyCharArray)]

9
  • 1
    public static readonly char[] MyCharArray= new char[]{'a','b','x','c'}; Commented Feb 7, 2022 at 10:46
  • 2
    Note that that won't make your array constant -- the readonly will stop people from doing MyClass.MyCharArray = new[] { ... }, but won't stop them from doing MyClass.MyCharArray[0] = ... Commented Feb 7, 2022 at 10:47
  • It needs to be const because I need to use it as a argument for custom data annotation validation. Ex: [MyCustumValidation(MyClass.MyCharArray)] Commented Feb 7, 2022 at 10:51
  • It needs to be passed through the controller. Commented Feb 7, 2022 at 10:57
  • 2
    Attributes allow only a limited set of types since they need to be embeddable in the metadata; arrays of any kind are out. You could use something like MyCustomValidation(MyCustomValidator), that is, pass a type that performs the validation. Alternatively, you could simply use a string to represent a collection of characters -- a slight abuse of the mechanism but it would allow you to stick with attributes. Commented Feb 7, 2022 at 11:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.