Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

c# - Why can I create a class named "var"?

Isn't var a keyword in C#? But why can I do this:

public class var { }

public class main
{
    public static void main(string[] args)
    {
        var testVar = new var();
    }
}

The var that is used in the code is the var class that is declared before the main class. And the compiler doesn't even complain.

While when I do this:

public class int { }

or this:

public class true { }

The compiler said that int or true is a keyword and cannot be used like that. Why is it not the same with var?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

var is not a keyword according to this list.

it is a contextual keyword, so from the context the compiler is able to decide which is your class and which is the contextual keyword, and no confusion arises.

a contextual keyword is:

used to provide a specific meaning in the code, but it is not a reserved word in C#.

so as its not reserved you can use it.

As pointed out in the comments above there is a discussion of the differences as well as a list of the various keywords and contextual keywords added at each version of c# on Eric Lipperts blog

It is interesting to note that since the set of keywords were decided upon in C#1.0 there have been no additions, so as to preserve backwards compatibility.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...