No var for me in the foreach

Posted by Jonas Elfström Tue, 09 Jun 2009 20:24:00 GMT

In C# 3.0 we got type inference or implicit typing as Microsoft likes to call it. As a Ruby programmer I've got a thing for essence over ceremony and those repetive declarations in C# (and Java) has always bothered me. So of course I quickly put var in my tool belt. If I want to create a certain object why should I have to state that twice?

1
2
3
4
// C# 2.0
Dictionary<Customer, List<PhoneNumber>> phonebook = new Dictionary<Customer, List<PhoneNumber>>(); 
// C# 3.0
var phonebook = new Dictionary<Customer, List<PhoneNumber>>();

Still you should use it with care. I've seen:

1
2
var i = 5;
var s = "This stmt is unprovable!";

And frankly, I do not agree.

A couple of days ago I almost thought I found a bug or limitation in the C# compiler. Something like the following would not compile:

1
2
3
4
5
6
7
String html = "<a href='http://is.gd/Uoip'>Recursion</a>,\r\n" +
              "see <a href='http://is.gd/Uoip'>recursion</a>.";
String links="";
var matches = Regex.Matches(html, "(a href=')(.*)('>)");
foreach (var match in matches) {
    links+=match.Groups[2]+"\r\n";
}

The compiler complained that Object had no Groups method. How come it could not see that Regex.Matches returned a MatchCollection and that that collection was populated with Match objects? Then it dawned on me. Back in the dark ages of C# 1.x we did not have generics. MatchCollection is an old class that implements ICollection and not ICollection(T) so the compiler could not infer the type. A quick change to:

foreach (Match match in matches) {

and we were good to go.

Posted in C# | no comments

Comments

Comments are closed