Force usage of “var” to be parsed as keyword rather than class name

Viewed 369

Is it possible to force C# compiler to treat var as a keyword and not as a class identifier when a class of name var is declared?

public class var
{
}

public class A
{
}

public class Program
{
    public static void Main()
    {
        var a=new A{};  // Cannot implicitly convert type 'A' to 'var'
    }
}

https://dotnetfiddle.net/O1wVoO

3 Answers

In your code, you can no longer use var as a keyword within the context.

var is a contextual keyword (there are two types of keywords: normal and contextual), where it behaves like a keyword within its respective contexts where it is used as a type name, but can still be used as an identifier (not reserved).

You declared it as class name therefore it loses its special meaning within the context.

Can you declare var class name as @var and check. @forces keywords to behave like variables.

yes of course you can do that:

namespace vartest
{

    public class var {
        public var()
        {
            MessageBox.Show("It is me!");
        }
    }
}
namespace myform {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            vartest.var theVar = new vartest.var();
            var a = "whatever";
        }
    }
}

As you can understand the trick is in the namespace ;-) Thus in your case to protect the c# var, define your var class at its own namespace which you should not be "using".

Cheers

Related