I noticed something that seems odd in the following code:
MatchCollection mc = Regex.Matches(myString, myPattern);
foreach(var match in mc)
Console.WriteLine(match.Captures[0]); // <-- this line is invalid, unless I replace 'var' above with 'Match'
The variable match is of type Object rather than Match. I am used to enumerating collections using var with no issues like this. Why is MatchCollection different?
MatchCollectionwas written before .NET 2, so it just implementsIEnumerablerather thanIEnumerable<T>. However, you can useCastto fix this very easily:If you give the variable an explicit type, like this:
… then the C# compiler inserts a cast on each item for you automatically. This was required in C# 1 to avoid having casts all over your code.
(Logically even with
varthere’s a conversion involved – but it’s always from one type to the same type, so nothing actually needs to be emitted.) See section 8.8.4 of the C# 4 spec for more details.