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?
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.
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.
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.
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.
It is not possible to use implicit variable declaration if you name a class var
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With