Why that is possible to define a class named var o

2020-04-29 02:21发布

问题:

Today I noticed we can define a class named var or dynamic. First, I thought it's not possible because these are special keywords and cannot be used as a Class name.But then I tried it,and I'm surprised. Here is a strange situation,when I define two class:

class var
{

}

class dynamic
{

}

And use them like this:

It doesn't give me any error.But when I try to Run my program it gives this error:

Cannot implicitly convert type string to dynamic

But As you may have noticed, my dynamic class behave like a standart C# class.When I try this:

 dynamic d = new dynamic();

I got this error:

Cannot instantiate dynamic object.

Let's look at var:

In this case var is still evaluated as implicit type definition keyword and my variable type infer as string.(notice that it's color is green not blue which is class name color).But when I Run the program it gave me the same exception:

Cannot implicitly convert type string to var

But interestingly when I try to create a new var instance like this:

var d = new var();
Console.WriteLine(d.GetType());

It doesn't give me any exception and I get this output:

ConsoleApplication3.var

Now after all of these I'm confused.I'm wondering what is the difference here and why compiler let us to create classes named var and dynamic,It doesn't give me any error when I creating a class named dynamic but if I try to create instance of dynamic I'm getting an error.But it doesn't give me any error if I try to create a var instance.Isn't that confusing ? I'm waiting for clear explanation.

Note: Sorry for my bad english and grammar mistakes.

回答1:

These are called contextual keywords.
They only behave as keywords if you don't have your own types with those names.

The point of this is to allow exactly what you just did.

Because these keywords were introduced by newer versions of C# (3.0 and 4.0), it's possible (though unlikely) that some existing codebases have classes with those names, just like you made.

Therefore, if the compiler sees such classes, it will compile exactly the way it used to and treat them as regular classes rather than keywords.



标签: c# dynamic var