Tuesday, August 23, 2011

Use keyword as an identifier in C#


Keywords are reserved by compiler so you can’t use it as identifier in your application. If you really need to use keyword as an identifier in your application you can achieve this using @ symbol. Let’s have a look on below example.

public class class //Illegal
{
       public int int =5; // Illegal
}

In above code snippet I have used ‘class’ and ‘int’ as an identifier which is illegal we can’t use keywords as an identifier. If you want to use keyword as identifier you have to use @ prefix with keyword see below example.

public class @class
{
       public int @int = 5;
}


public class MyClass
{
       public static void Main()
       {
              @class cls = new @class();
              Console.WriteLine(cls.@int.ToString());
       }
}
Output
5

This way you can use keyword as an identifier in your application.

Note – Some keywords can be used without using @ prefix like from, where, orderby, yield, var, join etc.

public static void Main()
{
       int where = 5;
       Console.WriteLine(where.ToString());
}

1 comment:

  1. I also do agree with the stuff you shared, Thanks that's a wonderful post.

    PIC Bonus

    ReplyDelete