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)]

makaMa
  • 11
  • 3
  • 1
    `public static readonly char[] MyCharArray= new char[]{'a','b','x','c'};` – Guru Stron Feb 07 '22 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] = ...` – canton7 Feb 07 '22 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)] – makaMa Feb 07 '22 at 10:51
  • It needs to be passed through the controller. – makaMa Feb 07 '22 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. – Jeroen Mostert Feb 07 '22 at 11:02
  • tnx @JeroenMostert, I had already read this. Thanks for the idea. – makaMa Feb 07 '22 at 11:04
  • @makaMa you can do `[MyCustomValidation(new char[]{'a','b','x','c'})]` but you can't declare it as a const and/or use one created somewhere else. But you can use `string` or subclass from `MyCustomValidation` and provide those values from the child class. – Guru Stron Feb 07 '22 at 14:12
  • @GuruStron How can I provide it form the subclass? – makaMa Feb 07 '22 at 14:37
  • @makaMa via constructor for example. Without seeing the attribute it is hard to tell. – Guru Stron Feb 07 '22 at 16:13

0 Answers0