Can we create a class called "class"?

Let's forget why I need this.

Is it possible to create a class called "class".

The following is a compilation error code, since the class is the reservation keyword.

public class class { } 

so is there any hack or way to trick the c # compiler? :)

This question was asked by the interviewer in my last interview, and he told me that this is possible.

+6
source share
3 answers

You can use:

 public class @class { } 

But why do you need this?

Keywords C #

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


What I learned from this answer was that new keywords will not be added globally, but only as contextual keywords, so as not to disrupt programs written in earlier versions. You will find the list in the link above.

So interesting, this is really (better: compilation) 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 that. It will break your other code where you used var or dynamic before.

+21
source

Another alternative is through Unicode

 using System; public class Program { public static void Main() { cl\u0061ss a = new cl\u0061ss(); Console.WriteLine(a.GetType().Name); } } public class cl\u0061ss { } 

Note : Console.WriteLine() will print the class

DotNetFiddle link here .

+8
source

Most programmers use the underscore character '_' at the beginning of a variable name or in general if it is a reserved word, for example.

 public class _class { } 

variable declaration example

 int _int; 
-3
source

Source: https://habr.com/ru/post/984490/


All Articles