S h o r t S t o r i e s

// Tales from software development

C# array initialisation

leave a comment »

I often define char arrays inline when using the String Split() method, e.g.

string myStrings[] = myStringList.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);

Earlier today I wrote a similar line but despite the source string containing several ‘;’ delimiters, the result was a string array containing a single element.

It wasn’t immediately obvious what my mistake was but when I looked very carefully I realised that I had miscoded the line as:

string myStrings[] = myStringList.Split(new char[';'], StringSplitOptions.RemoveEmptyEntries);

So, what does this do ?

The char constant ‘;’ is evaluated as an int. i.e. Ord(‘;’) = 59. So, this line is effectively:

string myStrings[] = myStringList.Split(new char[59], StringSplitOptions.RemoveEmptyEntries);

which means, create an array of char with 59 elements. Each element will have a value of zero.

Not at all what I intended…

The easiest way to see this is to type this into Visual Studio’s Interactive Window:

new char[';']

and you’ll see it evaluated as:

{char[59]}
    [0]: 0 ''
    [1]: 0 ''
    [2]: 0 ''
    [3]: 0 ''
    [4]: 0 ''
    [5]: 0 ''
    [6]: 0 ''
    [7]: 0 ''
    [8]: 0 ''
    [9]: 0 ''
    [10]: 0 ''
    [11]: 0 ''
    [12]: 0 ''
    [13]: 0 ''
    [14]: 0 ''
    [15]: 0 ''
    [16]: 0 ''
    [17]: 0 ''
    [18]: 0 ''
    [19]: 0 ''
    [20]: 0 ''
    [21]: 0 ''
    [22]: 0 ''
    [23]: 0 ''
    [24]: 0 ''
    [25]: 0 ''
    [26]: 0 ''
    [27]: 0 ''
    [28]: 0 ''
    [29]: 0 ''
    [30]: 0 ''
    [31]: 0 ''
    [32]: 0 ''
    [33]: 0 ''
    [34]: 0 ''
    [35]: 0 ''
    [36]: 0 ''
    [37]: 0 ''
    [38]: 0 ''
    [39]: 0 ''
    [40]: 0 ''
    [41]: 0 ''
    [42]: 0 ''
    [43]: 0 ''
    [44]: 0 ''
    [45]: 0 ''
    [46]: 0 ''
    [47]: 0 ''
    [48]: 0 ''
    [49]: 0 ''
    [50]: 0 ''
    [51]: 0 ''
    [52]: 0 ''
    [53]: 0 ''
    [54]: 0 ''
    [55]: 0 ''
    [56]: 0 ''
    [57]: 0 ''
    [58]: 0 ''

Advertisements

Written by Sea Monkey

January 8, 2013 at 8:00 pm

Posted in Debugging, Development

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: