Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we create class with name "class"?

Tags:

c#

Lets forgot about why I need this.

Can we create a class with name "class".

Below code resulted in compilation error as class is a reserve keyword.

public class class
{

}

so is there any hack or a way to fool C# compiler? :)

This Question was asked by interviewer in my last interview and he told me it is possible.

like image 200
Jinesh Jain Avatar asked Mar 31 '15 09:03

Jinesh Jain


1 Answers

You could use:

public class @class
{ 

}

But why do you want that?

C# Keywords

Keywords are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a valid identifier but if is not because if is a keyword.


What i've learned from this answer was that new key-words won't be added globally but only as contextual key-words to avoid breaking programs written in earlier versions. You find a list in the link above.

So interestingly enough this is valid(better: compiling) code:

public class var
{
    public void foo()
    {
        var var = new var();
    }
}

Here's another one:

public class dynamic
{
    public void foo()
    {
        dynamic dynamic = new dynamic(); 
    }
}

But never do this. It will break your other code where you've used var or dynamic before.

like image 102
Tim Schmelter Avatar answered Oct 20 '22 18:10

Tim Schmelter