4

Possible Duplicate:
Why can't the C# constructor infer type?

Why is the following true:

var foo = new KeyValuePair(3,4); //doesn't compile!
var boo = new KeyValuePair<int,int>(3,4); //works fine!

I would think both lines would be legal, since the type can be (should be) inferred from the parameters. Explanation?

Community
  • 1
  • 1
Brent Arias
  • 29,277
  • 40
  • 133
  • 234
  • This one's got me stumped too. The only thing I can think of is that it's because it's a constructor rather than a regular method, but I can't see why that would make any difference. – Bennor McCarthy Sep 24 '10 at 02:50
  • @Ben, yup, a dup. And the question you referenced is answered by Eric Lippert, so I'd defer to his response. ;) – Kirk Woll Sep 24 '10 at 02:53
  • Where is the link to the other question that this one duplicates? – jgauffin Sep 24 '10 at 06:54

1 Answers1

3

Simply put, type inference only works on methods, not constructors. The reason for this is simple, constructors do not take type arguments, only types and methods do. To wit, KeyValuePair is an undefined type. Remember, it is possible, for example, to have the following types: Action, Action<T>, Action<T1, T2>, etc.

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195