Friday, 1 July 2011

C# const char[]

Today i learnt, to my dismay, that you can't have a char array and make it a const

In fact, the compiler told me:

"A const field of a reference type other than string can only be initialized with null."

So after some searching i found that i could either:

1. Use a string type and make it a const
 - but i need to pass back a char[] to i'd have to do some converting of sorts...

2. Use an ENUM
 - again i'd need to do some converting but there is always the convenient ENUM.GetValues() method but that'll only return the int values...

So instead, i declared a private local char[] variable as well as a public Accessor method but no Mutator, effectively then making it a 'const':

private static char[] _digits = {'0','1','2','3','4','5','6','7','8','9'};

/// <summary>
/// An array with characters representing digits from 0 to 9
/// </summary>
public static char[] DIGITS
{
    get { return _digits; }
}

2 comments:

  1. Just to be clear, when you say that you could use a string, you are talking about using a string as in:

    const string digits = "0123456789";

    and not an array of const strings, such as:

    const string[] digits = {"0","1","2","3" ...};

    Because the latter will still give the same compiler error. Agreed?

    It seems to me that what you are doing could just as well be accomplished with:

    private static readonly char[] digits = {'0','1', ..}

    ReplyDelete
  2. Why not private readonly static char[] _digits = {'0','1','2','3','4','5','6','7','8','9'}; ?

    ReplyDelete