What is Identifiers in C Sharp? Can Identifiers have same name as Keywords?

Answer includes definition of Identifiers and keywords in C sharp. We will also be answering the best practice if they have same name.

Identifier: Identifier is a name given to variables, classes, functions and interfaces etc.

Identifiers name can be combination of letters, numbers, and underscores, but, cannot start with a number or else error.

Keyword: Keywords are predefined reserved identifiers built into C# that cannot be used as a user identifiers. For example, int, class, interface, abstract and new etc. all are reserved keywords.

Below is the c# code example with comments for keywords and identifiers.

//Identifiers and Keywords

//class : keyword
//myclass: identifier
class myclass {
    //int : keyword
    //val : identifer
    int val;

    // public, return and int : keyword
    //X : function identifer
    public int X() { return val; }//function identifier X
}
//interface : keyword
//IInterface: identifer
public interface IInterface { }//IInterface and interface identifier

What if an Identifier and a Keyword have same name?

Identifier and keyword cannot be of same name or else compiler will flash an error.

For example, if we use “int int =10;//(keyword and identifier same)” instead of “int var =10;” compiler will flash an error.

However, if we want to use an identifier with the same name as keyword, we have to prefix the identifier with “@” symbol.

For example, int @int is a valid identifier in C#.

In below working sample, we have used “@new” and “@int” for same name of keyword and identifier.

//Use @before identifers in case they have same name as keywords.
class A
{
    public void X()
    {
        int a = 10;//OK
        //int int=10;//compiler error: identifier int is a keyword.
        int @int = 10;//OK  
        Console.WriteLine("Val:" + @int);
    }
}

class Sample
{
    static void Main(string[] args)
    {
        A a = new A();
        //  A new = new A();//Error
        A @new = new A();//OK
        @new.X();
    }
}


Best Practice

We can use the keyword as an identifier prefixing with @ symbol, but, it is not a good programming practice, as it is always better keep them isolated for readability purpose.

But at some point of time it can be a useful feature. For example, a third party library written in a different language can have variables or identifiers that may conflicts with the keyword in C#.



Leave a Comment