8

I was reading about Implicitly Typed Local Variables (var) on

http://msdn.microsoft.com/en-us/library/bb384061.aspx

It states one restriction :

If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

Can anybody explain what is mean by statement with C# example?

1 Answer 1

12

That if you do this:

class var
{
    public static implicit operator var(int value)
    {
        return new var();
    }
}

var myVar = 5;

The myVar will be of type var and not of type int.

(the operator I've added is so that there is an implicit conversion from int to var).

This rule was inserted because var wasn't a reserved keyword in C# (and still isn't... If you look here you'll see it's a "contextual keyword"), so a class/struct/enum named var was valid in C# 2.0 .

  • If a type named var is in scope: if there is a class/struct/enum named var that is in scope (so "reachable" by simply writing var, without having to use a namespace)

  • then the var keyword will resolve to that type name: then var means "your user defined type" and not "the keyword var"

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.