Keywords In C#
Keywords are reserved, predefined identifiers in C# that have a specific meaning for the compiler. They serve as essential building elements for creating program statements in C#.
Properties of Keywords
Predefined Meaning: The compiler is already aware of the exact meaning of each of the 77 keywords in C#. The purpose of a keyword is automatically understood by the C# compiler.
Lowercase Letters: Every C# keyword is defined in lowercase characters and needs to be used only in this context.
Unchangeable Meaning: Users are unable to change a keyword’s precise meaning.
Reserved Names: As user-defined names, keywords cannot be applied to classes, variables, functions, arrays, pointers, interfaces, or namespaces.
Action Specification: Each keyword indicates a specific function or represents an object that the compiler should carry out.
Number of Keywords
There are 77 (seventy-seven) keywords in C#. In later iterations of the language, a few keywords were added.
Contextual Keywords
C# offers contextual keywords in addition to reserved keywords. Contextual keywords are identifiers that are unique to a particular code context. The terms get and set are examples.
Relationship with Identifiers
To uniquely identify an entity in a C# program, such as a variable, function, class, or namespace, a user-defined name is called an identifier. It is important to remember that keywords shouldn’t be utilised as identifiers. However, a programmer can prefix a keyword with the @ character if they need to utilise it as an identifier. The compiler only takes into account the first 31 characters of an identifier, even if there is no strict limit to its length. Additionally, within their scope, identifiers must be unique.
Code Examples
Examples of keywords and their usage, including both acceptable and invalid identifiers, are shown below:
General Program Structure Keywords
A simple C# program structure uses a number of keywords, as shown in the following code snippet:
using System; // 'using' is a keyword to include a namespace
namespace HelloWorldApplication // 'namespace' is a keyword for organizing code into logical groups
{
class HelloWorld // 'class' is a keyword for declaring a class
{
public static void Main(string[] args) // 'public', 'static', 'void', 'string' are keywords
{
/* my first program in C# */ // Comments are ignored by the compiler
Console.WriteLine("Hello World"); // 'Console' is a class, 'WriteLine' is a method
Console.ReadKey();
}
}
}
Output
Hello World
using
: When namespaces are imported using this term, you can refer to types within of them without giving their complete qualified name.
namespace
: This term creates a declarative region that gives identifiers a scope, arranging code logically into groups and avoiding name clashes.
class
: To declare a class a blueprint for building objects use this term.
public
: The class member can be accessed from any other code by using an access modifier keyword.
static
: A term that indicates the member is a part of the class as a whole, not just one particular instance.
void
: A keyword indicating that no value is returned by a procedure.
string
: A keyword that serves as the System’s alias.A string is a class that represents a series of characters.
Main
: This function is where all C# applications start.
Keyword Usage in Expressions and Statements
Commonly used keywords in statements and expressions include if, int, return, true, new, this, and operators (>=, +, =):
using System;
class ExampleKeywords
{
int _income = 0; // '_income' is an identifier, 'int' is a keyword
public void CheckIncome(int income) // 'public', 'void', 'int' are keywords
{
if (income >= 10000) // 'if' is a keyword for conditional statements
{
this._income = income; // 'this' refers to the current instance of the class
System.Console.WriteLine("Income set to: " + this._income); // 'System', 'Console', 'WriteLine' are part of the standard library
}
else
{
this._income = 0;
System.Console.WriteLine("Income too low, reset to 0.");
}
}
public bool IsEligible() // 'bool' is a keyword for boolean type
{
if (this._income > 5000)
{
return true; // 'return' is a keyword to exit a method and optionally return a value
}
return false;
}
// This is the entry point of the program
static void Main(string[] args)
{
// Create an instance of the ExampleKeywords class
ExampleKeywords myExample = new ExampleKeywords(); // 'new' keyword used here
// Test the methods
myExample.CheckIncome(12000);
Console.WriteLine("Is eligible (after 12000): " + myExample.IsEligible()); // Should be true
Console.WriteLine("\n---");
myExample.CheckIncome(3000);
Console.WriteLine("Is eligible (after 3000): " + myExample.IsEligible()); // Should be false
Console.WriteLine("\n---");
myExample.CheckIncome(7000); // Income set to 0 as it's below 10000
Console.WriteLine("Is eligible (after 7000): " + myExample.IsEligible()); // Should be false (because _income becomes 0)
}
}
Output
Income set to: 12000
Is eligible (after 12000): True
---
Income too low, reset to 0.
Is eligible (after 3000): False
---
Income too low, reset to 0.
Is eligible (after 7000): False
Valid and Invalid Identifiers
Direct usage of keywords as identifiers is not possible.
Valid Identifiers | Invalid Identifiers | Explanation |
a , b | break | break is a reserved keyword. |
_a | 123a | Identifiers cannot start with a digit. |
_123 | str- | Identifiers cannot contain special characters like - . |
pi | a b | Identifiers cannot contain embedded spaces. |
value , Value , vAlue | C# is case-sensitive, so these are treated as different identifiers. |
A keyword must be prefixed with @: in order to be used as an identifier.
// Using a keyword as an identifier with the @ prefix
int @class = 10; // '@class' is a valid identifier even though 'class' is a keyword
System.Console.WriteLine(@class);
Although it is generally not advised for good programming practice, this is acceptable.
Similar to a hammer for hammering or a screwdriver for screws, keywords are specialised tools in a programmer’s toolbox, each having a very definite, fixed function. Contrarily, identifiers are the names you apply to your own works (such as “my_house” or “project_plan”). You wouldn’t call your house “hammer” because the word already has a very specific and practical meaning in the construction industry.
You can also read C# LINQ (Language Integrated Query) Features And Concepts