Hi,
I get the feeling that I am missing something with regards to casting.
The CopyTo method allows me to copy the contents of a collection into an
array. My collection is a MatchCollection produced by Regex. The
Collection's entries are all valid strings. If I CopyTo to a string array
it compiles ok, but fails at run time with an InvalidCastException. It
works if I CopyTo an object array. ... does this mean that the
MatchCollection's CopyTo should only be used with arrays of objects ?
If I use the array of objects how can I use IndexOf to find the element
that contains a specific string ? The command I was using is, where I was
looking for the word "two":
int ix = Array.IndexOf(WordArray,(object)"two"); // fails
It all works if I don't use CopyTo, but instead step through the
collection using a for loop, and doing a cast to string as follows:
string[] MyStringArrayxx = new string[mc.Count];
for (int i2 = 0; i2 < mc.Count; i2++) {
MyStringArrayxx[i2] = mc[i2].ToString();
}
ix = Array.IndexOf(MyStringArrayxx,"two");
Console.WriteLine("String array -> {0}",ix);
I get the feeling that I missing something. ie. is there a way to
overcome the cast exception with CopyTo, or is there a way to use IndexOf
with an array of objects ?
Thanks
Barry Mossman
Source in context follows:
Regex regex = new Regex(
@"[^\s]\w*",
RegexOptions.IgnoreCase
| RegexOptions.Multiline
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
string stx = "One or two two words.";
MatchCollection mc = regex.Matches(stx);
Console.WriteLine("captures = {0}",mc.Count);
for (int i = 0; i < mc.Count; i++) {
Console.WriteLine("match = {0}", mc[i].Value);
}
try {
Console.WriteLine(mc.GetType());
Console.WriteLine(mc[0].GetType());
string[] StringArray = new string[mc.Count];
//mc.CopyTo(StringArray,0); // causes InvalidCastException
// don't know how to use IndexOf with objects
object[] WordArray = new object[mc.Count];
mc.CopyTo(WordArray,0);
int ix = Array.IndexOf(WordArray,(object)"two"); // fails
Console.WriteLine("Object array -> {0}",ix);
// all ok if I step through and convert all entries
// to strings
string[] MyStringArrayxx = new string[mc.Count];
for (int i2 = 0; i2 < mc.Count; i2++) {
MyStringArrayxx[i2] = mc[i2].ToString();
}
ix = Array.IndexOf(MyStringArrayxx,"two");
Console.WriteLine("String array -> {0}",ix);
}
catch (Exception ex) {
Console.WriteLine(ex);
}
Console.ReadLine();