Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrictions apply to implicitly-typed variable declarations

Tags:

c#

.net

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?

like image 504
Tanaji Kamble Avatar asked Aug 28 '13 07:08

Tanaji Kamble


1 Answers

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"

like image 57
xanatos Avatar answered Oct 17 '22 22:10

xanatos