Wednesday, May 21, 2008

Another day, another gotcha.

While working with regular expressions I was matching some input string to a pattern with one group capture (is it the correct name?). I made a regex.Match() thing, got a match and since it was just a test code, I wen stright for getting the second group out of the match (first being the whole match):

DoSomething(match.Groups[1].Value);

I was pretty much expecting an IndexOutOfRangeException, or something similar, in case there were no matches. To my surprise I got no exception! To the contrary I got a result, an empty one, but a result.

Quick peek inside the code and it came out, that that's just how GroupCollection's indexer is implemented. It returns an empty group in case you try to get one that doesn't exist.

Is it intuitive? I seriously doubt it. That's a first time I see a collection with an indexer, that allows me to access elements by index that is beyond the collection's elements count!

I don't like when those kinds of things happen...

Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview