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.