;

C# Keywords


C# is a powerful, versatile, and widely-used object-oriented programming language. At its core, it uses keywords—reserved words that have predefined meanings within the C# compiler. These keywords are critical to the structure and functionality of C# programs. In this tutorial, we'll explore C# keywords, providing short details about each of them, explaining their use cases, and helping you understand how to integrate them into your code.

What Are Keywords in C#?

Keywords in C# are reserved words that have special meanings and cannot be used as identifiers (such as variable names, function names, etc.). These keywords are integral to the language's syntax and provide instructions to the compiler on how to handle data and actions within the program.

Categories of C# Keywords

C# keywords can be categorized into several groups based on their functionality:

  1. Access Modifiers
  2. Data Types
  3. Control Flow Statements
  4. Modifiers
  5. Method Parameters
  6. Contextual Keywords
  7. Exception Handling
  8. Object-Oriented Programming (OOP)
  9. Other Keywords

1. Access Modifiers

Access modifiers control the visibility and accessibility of classes, methods, and fields. They are crucial for encapsulation in C#.

  • public: Makes members accessible from anywhere.
  • private: Restricts access to within the same class.
  • protected: Allows access within the same class and derived classes.
  • internal: Makes members accessible within the same assembly.
  • protected internal: Combines protected and internal, allowing access within the same assembly or from derived classes.
  • private protected: Members are accessible within the same class or derived classes in the same assembly.

2. Data Types

C# supports various data types, which define the kind of data that can be stored and manipulated within a program.

  • int: Represents integer numbers.
  • double: Represents double-precision floating-point numbers.
  • float: Represents single-precision floating-point numbers.
  • char: Represents a single character.
  • string: Represents a sequence of characters (a string).
  • bool: Represents a Boolean value (true or false).

3. Control Flow Statements

Control flow keywords control the flow of program execution based on conditions or loops.

  • if: Executes a block of code if a condition is true.
  • else: Executes a block of code if the if condition is false.
  • switch: Selects one of many code blocks to execute.
  • case: Defines a specific condition within a switch statement.
  • while: Loops through a block of code as long as a condition is true.
  • for: Loops through a block of code a specified number of times.
  • foreach: Loops through elements in a collection.
  • do: Executes a block of code at least once, then repeats based on a condition.
  • break: Exits from a loop or switch statement.
  • continue: Skips the current iteration of a loop and moves to the next.
  • return: Exits a method and optionally returns a value.
  • goto: Transfers control to a labeled statement.

4. Modifiers

Modifiers provide additional information about data, methods, and classes.

  • static: Indicates that a method or variable belongs to the class, not an instance.
  • const: Defines a constant value that cannot be changed.
  • readonly: Defines a field that can only be assigned a value during declaration or within a constructor.
  • sealed: Prevents a class from being inherited.
  • abstract: Defines a method or class that must be implemented or inherited.
  • virtual: Allows a method to be overridden in derived classes.
  • override: Indicates that a method overrides a base class method.
  • async: Used to declare asynchronous methods.

5. Method Parameters

C# offers several keywords to handle method parameters.

  • params: Allows a method to accept a variable number of arguments.
  • ref: Passes arguments by reference.
  • out: Similar to ref, but it requires that the method assign a value before the method returns.
  • in: Passes parameters by reference but prevents modification within the method.

6. Contextual Keywords

Contextual keywords have special meaning in certain contexts but can also be used as identifiers.

  • var: Automatically infers the type of a variable.
  • dynamic: Declares variables whose types are resolved at runtime.
  • async: Marks methods as asynchronous.
  • await: Suspends execution of an asynchronous method until the awaited task completes.
  • yield: Returns each element of a collection one at a time.
  • partial: Allows methods and classes to be split across multiple files.

7. Exception Handling

Exception handling is essential for robust applications, and these keywords help manage errors and exceptions.

  • try: Defines a block of code to test for errors.
  • catch: Defines a block of code to handle errors.
  • finally: Defines a block of code that runs regardless of whether an error occurred.
  • throw: Manually raises an exception.

8. Object-Oriented Programming (OOP)

C# is inherently object-oriented, and these keywords support its OOP features.

  • class: Declares a class.
  • interface: Declares an interface, which defines methods that must be implemented by a class.
  • new: Instantiates objects or hides inherited members.
  • this: Refers to the current instance of the class.
  • base: Refers to the base class and is used to call its constructors or methods.
  • is: Checks if an object is of a specific type.
  • as: Performs safe type casting.

9. Other Keywords

These keywords provide general functionality and are used in different contexts.

  • null: Represents a null value (no value).
  • default: Specifies the default value of a type.
  • typeof: Gets the System.Type of a type.
  • sizeof: Returns the size in bytes of a value type.
  • checked: Enables overflow checking for arithmetic operations.
  • unchecked: Disables overflow checking for arithmetic operations.
  • lock: Ensures that one thread does not enter a critical section of code while another thread is in it.
  • volatile: Indicates that a field can be modified by multiple threads.
  • using: Allows the use of types defined in a namespace and disposes of resources automatically.

Complete List of C# Keywords

Here’s the comprehensive list of C# keywords:

Keyword Description
abstract Indicates that a class or method is incomplete and must be implemented in derived classes.
as Performs a conversion between compatible types.
base Refers to the base class of the current instance.
bool Represents a Boolean value (true or false).
break Exits a loop or switch statement.
byte Represents an 8-bit unsigned integer.
case Defines a branch in a switch statement.
catch Defines a block of code to handle errors.
char Represents a single 16-bit Unicode character.
checked Enables overflow checking for integral-type arithmetic operations.
class Defines a class.
const Indicates that a field is a constant and cannot be modified.
continue Skips the current iteration of a loop and proceeds to the next iteration.
decimal Represents a 128-bit precise decimal value.
default Defines the default case in a switch statement.
delegate Defines a delegate type.
do Executes a block of code once, and then repeats as long as a specified condition is true.
double Represents a double-precision floating point.
else Executes a block of code if the condition is false.
enum Defines an enumeration.
equals Indicates the equality operator for comparing objects.
event Declares an event in a class.
explicit Indicates an explicit conversion operator.
extern Indicates that a method is implemented externally.
FALSE Represents the Boolean value false.
finally Defines a block of code that executes after try and catch blocks.
fixed Locks a variable in place in memory.
float Represents a single-precision floating point.
for Executes a block of code a specified number of times.
foreach Iterates through a collection.
goto Transfers control to a labeled statement.
if Executes a block of code if a specified condition is true.
implicit Indicates an implicit conversion operator.
in Indicates that a variable is passed by reference.
int Represents a 32-bit signed integer.
interface Defines an interface.
internal Access is limited to the current assembly.
is Checks the type of an object.
lock Acquires a mutual-exclusion lock for a given object.
long Represents a 64-bit signed integer.
namespace Declares a namespace.
new Creates an instance of a type.
null Represents a null reference.
object The base type from which all other types derive.
operator Defines an operator overload.
or Used in some contexts for logical operations.
out Indicates that a variable is passed as an output parameter.
override Indicates that a method is overriding a base class method.
params Specifies a method parameter that takes a variable number of arguments.
private Access is limited to the containing type.
protected Access is limited to the containing type and types derived from it.
public Access is not restricted.
readonly Indicates that a field can only be assigned during declaration or in the constructor.
ref Indicates that a variable is passed by reference.
return Exits a method and optionally returns a value.
sbyte Represents an 8-bit signed integer.
sealed Indicates that a class cannot be inherited from.
short Represents a 16-bit signed integer.
sizeof Returns the size of a type in bytes.
stackalloc Allocates memory on the stack.
static Indicates that a member belongs to the type itself rather than an instance of the type.
string Represents a sequence of characters.
struct Defines a structure.
switch Executes one block of code among multiple choices.
throw Throws an exception.
try Defines a block of code to be tested for errors.
typeof Returns the Type object for a type.
uint Represents a 32-bit unsigned integer.
ulong Represents a 64-bit unsigned integer.
unchecked Disables overflow checking for integral-type arithmetic operations.
unsafe Indicates that code uses pointers and is not type-safe.
ushort Represents a 16-bit unsigned integer.
using Defines a scope at the end of which an object will be disposed.
var Implicitly typed variable declaration.
virtual Indicates that a method can be overridden in a derived class.
void Indicates that a method does not return a value.
volatile Indicates that a field can be accessed by multiple threads.
while Executes a block of code as long as a specified condition is true.
with Used in record types for non-destructive updates.
async Indicates that a method is asynchronous.
await Used to wait for an asynchronous operation.
dynamic Indicates that a variable can hold any type and resolves at runtime.
from Used in LINQ queries to specify the data source.
let Used in LINQ queries to create a range variable.
select Used in LINQ queries to specify the result shape.
where Used in LINQ queries to filter data.
join Used in LINQ queries to join two data sources.
group Used in LINQ queries to group data.
into Used in LINQ queries to define a new range variable after a grouping operation.
orderby Used in LINQ queries to sort data.
equals Indicates the equality operator for comparing objects.
by Used in LINQ queries to specify a grouping key.
final Used in some contexts to denote finalization.


Visit MSDN for more details about Keywords.

Summary

C# keywords are the building blocks of your code. Understanding these keywords is fundamental to mastering the language. As you progress in your learning, knowing when and how to use these keywords will make your code more efficient, readable, and maintainable.