Craig Gibbons' Lifeblog lifeblog://


C# – DelimitedStringToInt32Array, a useful conversion routine

Today I was presented with a mini programming challenge, that being, to convert a delimited string to an integer array. While this is by no means tough, I thought I'd post the code here in case anybody is interested. This type of routine is quite useful when, for example, passing a list of ID's in a QueryString. Of course this code is made available without any implied warranties and without liability to the author, yours truly.

private int[] DelimitedStringToInt32Array(string DelimitedString, string Delimiter) {
if(DelimitedString.Length == 0) {
return new int[0];

try {
string[] sourceArray = DelimitedString.Split(Delimiter.ToCharArray());
int[] destinationArray = new int[sourceArray.Length];
for(int i = 0; i < sourceArray.Length; i++) {
destinationArray[i] = Convert.ToInt32(sourceArray[i]);

return destinationArray;
} catch(InvalidCastException ex) {
throw new InvalidCastException("At least one of the source elements could not be cast to the destination type.", ex);

Filed under: Tech Leave a comment
Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.