Use Keywords as Variable Names

The preset group of reserved words with specific significance for the compiler in C# are known as keywords. So, in our applications, the C# keywords cannot be utilised as identifiers like variable names, class names, etc.

 Use keyword as variable names

In C#, you must use the @ prefix as a prefix for your variable names if you want to use Keywords as variable names (identifiers). For instance, the switch is not a valid identifier because it is a keyword and has a specific meaning for the compiler, whereas @switch is.

The example below shows how to use the reserved keywords as variable names in the C# programming language by adding the @ prefix.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
        public class @class
        {
            public int year;
        }
        class Program
        {
            static void Main(string[] args)
            {
                @class p1 = new @class();
                p1.year = 10;
                Console.WriteLine("Year: " + p1.year);
                Console.WriteLine("Press Enter Key to Exit..");
                Console.ReadLine();
            }
        }     
}

As you can see from the C# example above, we prefixed the variable name (@class) with the @ symbol to utilise the class keyword as a variable name.

The result of running the console application will be as displayed below.

.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories