Can you use implicit type variables with a class named `var`?

I just found out that the var keyword can be used as the class name:

 public class var // no problem here { } 

Now, if I overload the implicit casting operator, I can use my class in an interesting way:

 namespace MyApp { class Program { static void Main(string[] args) { var x = 1; // var is of type MyApp.var } } public class var { public implicit operator var(int i) { return new var(); } } } 

In such a scenario, is it still possible to somehow force the compiler to infer types? This blog entry says itโ€™s not possible (skip to the paragraph starting with โ€œOr, another exampleโ€), but maybe something has changed since 2009

+7
c # var
source share
1 answer

To make it short

It is not possible to use an implicit variable declaration if you name the class var .

Could the C # development team simply prohibit name classes to avoid confusing code?

No, because it can break some code written before a new var value appears in the language. All legacy codes with var as class names will no longer compile. And lately, I read that backward compatibility is very important for the C # development team.

+2
source share

All Articles