Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you take advantage of implicit type variables with a class named `var`?

Tags:

c#

var

I just found out that it is possible to use the keyword var as a class name:

public class var // no problem here
{
}

Now if I overload the implicit cast operator I can use my class in an interesting manner:

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 scenario, is it still possible to somehow make the compiler infer the types? This blog entry states that it is not possible (go to the paragraph starting with "Or, another example."), but maybe something changed since 2009?

like image 654
Kapol Avatar asked Aug 06 '15 16:08

Kapol


People also ask

What is the advantage of var keyword?

var requires less typing. It also is shorter and easier to read, for instance, than Dictionary<int,IList> . var requires less code changes if the return type of a method call changes. You only have to change the method declaration, not every place it's used.

What is the advantage of using var in C#?

By using “var”, you are giving full control of how a variable will be defined to someone else. You are depending on the C# compiler to determine the datatype of your local variable – not you. You are depending on the code inside the compiler – someone else's code outside of your code to determine your data type.

What are implicit type variables?

Implicitly typed variables are those variables which are declared without specifying the . NET type explicitly. In implicitly typed variable, the type of the variable is automatically deduced at compile time by the compiler from the value used to initialize the variable.

Should you always use var C#?

It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types. The complaint that var reduces readability is not shared by everyone.


1 Answers

To make it short

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

Can't the C# design team just disallow naming classes like that to avoid confusing code?

No, because that might break some code written before the new meaning of var was introduced in the language. All legacy code with var as class names would not compile anymore. And I read lately that backwards compatibility is very important for the C# designer team.

like image 153
Kapol Avatar answered Oct 12 '22 23:10

Kapol