Why can I create a class named “var”?

后端 未结 5 1858
-上瘾入骨i
-上瘾入骨i 2020-12-05 09:22

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)
    {
           


        
5条回答
  •  醉梦人生
    2020-12-05 09:59

    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.

提交回复
热议问题