Skip to main content

C# Keywords

C# Keywords

Many different reserved words or keywords are used in C# programming. They are categorised as described below. It is advised to properly get familiar with the categories, functionality, and usage of each of them before we move forward. If, somewhere, you feel you are not able to grasp the correct meaning, make a note of it and in the future specific examples where it is explicitly used, you would be able to recall and revise it.
Some examples for certain keywords can be viewed at: Link

1. Data Types and Modifiers

bool

  • Explanation: Represents a Boolean value that can be either true or false. It is an alias for the system type System.Boolean.

  • Example: bool isCoding = true;

byte

  • Explanation: Represents an 8-bit unsigned integer that can store values from 0 to 255.

  • Example: byte age = 25;

char

  • Explanation: Represents a single 16-bit Unicode character. It is enclosed in single quotes.

  • Example: char grade = 'A';

class

  • Explanation: Used to declare a reference type that can contain data members and function members. It is the fundamental building block of OOP in C#.

  • Example: class Player { }

const

  • Explanation: Specifies that the value of a field or local variable is constant and cannot be modified after compilation.

  • Example: const double Pi = 3.14159;

decimal

  • Explanation: Represents a 128-bit precise decimal type, ideal for financial and monetary calculations.

  • Example: decimal price = 19.99m;

double

  • Explanation: Represents a 64-bit double-precision floating-point number.

  • Example: double distance = 123.45;

enum

  • Explanation: Declares an enumeration, a distinct type consisting of a set of named constants.

  • Example: enum Days { Mon, Tue, Wed };

float

  • Explanation: Represents a 32-bit single-precision floating-point number, requiring an f or F suffix.

  • Example: float temperature = 36.6f;

int

  • Explanation: Represents a 32-bit signed integer type. It is the most commonly used data type for whole numbers.

  • Example: int count = 10;

interface

  • Explanation: Defines a contract that a class or struct must implement, containing only signatures without implementation details (prior to C# 8).

  • Example: interface IRepository { void Save(); }

long

  • Explanation: Represents a 64-bit signed integer type, used when values exceed the range of int.

  • Example: long population = 8000000000L;

object

  • Explanation: The root alias for System.Object. All types in C#, both reference and value types, inherit directly or indirectly from it.

  • Example: object data = "Hello World";

readonly

  • Explanation: Indicates that assignment to a field can only occur as part of the declaration or in a constructor of the same class.

  • Example: readonly string configFile;

sbyte

  • Explanation: Represents an 8-bit signed integer type, storing values from -128 to 127.

  • Example: sbyte level = -5;

short

  • Explanation: Represents a 16-bit signed integer type, storing values from -32,768 to 32,767.

  • Example: short index = 32000;

static

  • Explanation: Declares a member that belongs to the type itself rather than to a specific object instance.

  • Example: static void Main() { }

string

  • Explanation: Represents a sequence of zero or more Unicode characters. It is an alias for System.String.

  • Example: string name = "Alice";

struct

  • Explanation: Declares a value type that can encapsulate data and related functionality, usually smaller and more lightweight than a class.

  • Example: struct Point { public int X; public int Y; }

uint

  • Explanation: Represents a 32-bit unsigned integer type, storing values from 0 to 4,294,967,295.

  • Example: uint energy = 4000000000U;

ulong

  • Explanation: Represents a 64-bit unsigned integer type.

  • Example: ulong largeNumber = 123456789012345UL;

ushort

  • Explanation: Represents a 16-bit unsigned integer type, storing values from 0 to 65,535.

  • Example: ushort port = 8080;

void

  • Explanation: Used as the return type of a method to indicate that the method does not return a value.

  • Example: void LogMessage() { Console.WriteLine("Done"); }

volatile

  • Explanation: Indicates that a field can be modified by multiple threads that are executing at the same time, preventing compiler optimizations that assume single-threaded access.

  • Example: volatile bool _shouldStop;


What is the difference between Modifiers and Access Modifiers?

While all access modifiers are modifiers, not all modifiers are access modifiers.

Here is the fundamental difference between the two concepts in C#.

The Core Difference

Access Modifiers specifically control visibility and scope (who can see and use your code). They dictate whether another class, project, or assembly can access a member.

 

Modifiers (Non-Access Modifiers) control behavior and functionality (how your code behaves). They do not change who can see the code; instead, they alter how it executes, instantiates, or inherits.


 

2. Access Modifiers

There are 6 access modifiers formed by below 4 keywords.

internal

  • Explanation: Restricts access to types and members so they are only visible within the same assembly (project).

  • Example: internal class InternalHelper { }

private

  • Explanation: Restricts access to types and members so they are only visible within the same class or struct.

  • Example: private int _id;

protected

  • Explanation: Restricts access so a member is visible only within its own class and by derived class instances.

  • Example: protected void OnChanged() { }

public

  • Explanation: Allows unrestricted access to the type or member from any other code in the assembly or another assembly that references it.

  • Example: public string Title;

3. Control Flow and Statements

break

  • Explanation: Terminates the closest enclosing loop or switch statement in which it appears.

  • Example: while(true) { break; }

case

  • Explanation: Evaluates a label in a switch statement or expression to match against a given value.

  • Example: switch(x) { case 1: break; }

continue

  • Explanation: Passes control to the next iteration of the enclosing iteration statement in which it appears.

  • Example: for(int i=0; i<5; i++) { if(i==2) continue; }

default

  • Explanation: Specifies the default label in a switch statement, or produces the default value of a given type.

  • Example: int defaultValue = default(int);

do

  • Explanation: Executes a statement or a block of statements repeatedly until a specified expression evaluates to false; guarantees at least one execution.

  • Example: do { Console.WriteLine("Hi"); } while (condition);

else

  • Explanation: Identifies the conditional branch to execute when the preceding if condition evaluates to false.

  • Example: if (isReady) { } else { }

for

  • Explanation: Defines a loop that executes a block of statements while a specified condition evaluates to true, controlled by an initializer, condition, and iterator.

  • Example: for (int i = 0; i < 10; i++) { }

foreach

  • Explanation: Iterates through each element in a collection or array that implements the IEnumerable interface.

  • Example: foreach (var item in list) { }

goto

  • Explanation: Transfers the program control directly to a labeled statement.

  • Example: goto ErrorHandler;

if

  • Explanation: Selects a statement or block to execute based on the value of a Boolean expression.

  • Example: if (score > 50) { }

return

  • Explanation: Terminates execution of the method in which it appears and returns control (and an optional value) to the caller.

  • Example: return result;

switch

  • Explanation: Selection statement that chooses a single switch section to execute based on a pattern match with a match expression.

  • Example: switch (color) { case "Red": break; }

while

  • Explanation: Executes a statement or a block of statements repeatedly until a specified expression evaluates to false.

  • Example: while (x < 10) { x++; }


4. Method and Class Modifiers

abstract

  • Explanation: Indicates that a class or member is missing implementation and is intended to be implemented by derived classes.

  • Example: abstract class Shape { public abstract void Draw(); }

async

  • Explanation: Modifies a method, lambda expression, or anonymous method to indicate that it contains asynchronous operations.

  • Example: async Task FetchDataAsync() { }

await

  • Explanation: Suspends the evaluation of the enclosing async method until the asynchronous operation represented by its operand completes.

  • Example: var data = await client.GetStringAsync(url);

extern

  • Explanation: Indicates that a method is implemented externally, typically in an unmanaged DLL via P/Invoke.

  • Example: [DllImport("user32.dll")] public static extern int MessageBox(...);

new

  • Explanation: Explicitly hides a member inherited from a base class, or instantiates an object of a type.

  • Example: new public void Show() { } // or: var obj = new MyClass();

override

  • Explanation: Extends or modifies the abstract or virtual implementation of an inherited method, property, indexer, or event.

  • Example: public override string ToString() => "Custom";

partial

  • Explanation: Allows the definition of a class, struct, interface, or method to be split across multiple source files.

  • Example: partial class Form1 { }

sealed

  • Explanation: Prevents other classes from inheriting from it, or prevents overriding of specific virtual members in derived classes.

  • Example: sealed class FinalClass { }

unsafe

  • Explanation: Denotes a context or block of code that is permitted to perform direct memory manipulation using pointers.

  • Example: unsafe { int* p = &x; }

virtual

  • Explanation: Modifies a method, property, indexer, or event declaration and allows it to be overridden in a derived class.

  • Example: public virtual void Calculate() { }

5. Exception Handling

catch

  • Explanation: Defines a code block to execute when a specific exception is thrown inside a corresponding try block.

  • Example: catch (Exception ex) { Log(ex); }

finally

  • Explanation: Defines a code block that always executes after control leaves a try or catch block, used for resource cleanup.

  • Example: finally { connection.Close(); }

throw

  • Explanation: Signals the occurrence of an exception during program execution.

  • Example: throw new ArgumentNullException();

try

  • Explanation: Introduces a block of code to be monitored for exceptions during its execution.

  • Example: try { ProcessData(); } catch { }

6. Operators and Expressions

as

  • Explanation: Performs a runtime explicit type conversion safely, returning null if the cast fails instead of throwing an exception.

  • Example: string s = obj as string;

checked

  • Explanation: Enables overflow checking for integer-type arithmetic operations and conversions.

  • Example: checked { int x = int.MaxValue + 1; }

is

  • Explanation: Checks if the runtime type of an expression is compatible with a given type, or matches a pattern.

  • Example: if (obj is int number) { }

sizeof

  • Explanation: Obtains the size in bytes for an unmanaged type.

  • Example: int size = sizeof(int);

typeof

  • Explanation: Obtains the System.Type object representing a specified type at compile time.

  • Example: Type t = typeof(string);

unchecked

  • Explanation: Suppresses overflow checking for integer-type arithmetic operations and conversions.

  • Example: unchecked { int x = int.MaxValue + 1; }

7. Parameters and Generics

in

  • Explanation: Passes an argument to a method by reference but guarantees it cannot be modified by the called method. Also used in generics and foreach loops.

  • Example: void ReadOnlyRef(in int number) { }

out

  • Explanation: Indicates that a parameter is passed by reference and must be assigned a value inside the called method before returning.

  • Example: bool success = int.TryParse("123", out int result);

params

  • Explanation: Specifies a method parameter that takes a variable number of arguments as an array.

  • Example: void PrintAll(params int[] numbers) { }

ref

  • Explanation: Causes an argument to be passed by reference, meaning modifications to the parameter inside the method affect the variable in the calling code.

  • Example: void Update(ref int x) { x += 10; }

8. LINQ (Language Integrated Query) Keywords

ascending

  • Explanation: Contextual keyword used in LINQ query expressions to sort elements in increasing order.

  • Example: from n in nums orderby n ascending select n;

by

  • Explanation: Contextual keyword used in LINQ query expressions to specify the grouping key.

  • Example: from p in people group p by p.Age;

descending

  • Explanation: Contextual keyword used in LINQ query expressions to sort elements in decreasing order.

  • Example: from n in nums orderby n descending select n;

equals

  • Explanation: Contextual keyword used in a LINQ join clause to compare keys for equality.

  • Example: join c in customers on p.Id equals c.ProductId

from

  • Explanation: Contextual keyword that specifies the data source and iteration variable for a LINQ query expression.

  • Example: from item in collection select item;

group

  • Explanation: Contextual keyword that groups query results by a specified key.

  • Example: group student by student.Grade;

into

  • Explanation: Contextual keyword used to create a temporary identifier to store the results of a group, join, or select clause.

  • Example: group p by p.City into g select g;

join

  • Explanation: Contextual keyword used to join two data sources based on a matching key.

  • Example: from a in listA join b in listB on a.Id equals b.Id

let

  • Explanation: Contextual keyword that allows storing the sub-expression result of a query in a new variable.

  • Example: let upperName = user.Name.ToUpper()

on

  • Explanation: Contextual keyword used in a LINQ join clause to introduce the key tracking rule.

  • Example: join s in stores on p.StoreId equals s.Id

orderby

  • Explanation: Contextual keyword that sorts the elements of a query in ascending or descending order.

  • Example: from u in users orderby u.LastName select u;

select

  • Explanation: Contextual keyword that specifies the form or projection of elements returned by a query.

  • Example: from e in employees select e.Name;

where

  • Explanation: Contextual keyword that filters elements from a data source in a query, or adds constraints to a generic type parameter.

  • Example: where x > 10 or where T : class

9. Contextual and Miscellaneous Keywords

add / remove

  • Explanation: Used to define custom accessor behavior when client code subscribes or unsubscribes from an event.

  • Example: add { _myEvent += value; } remove { _myEvent -= value; }

alias

  • Explanation: Contextual keyword used to reference namespaces that have been given a global alias in compilation options.

  • Example: extern alias GridV1;

args

  • Explanation: Recognized implicitly in C# top-level statements to represent command-line arguments.

  • Example: if (args.Length > 0) { }

base

  • Explanation: Used to access members of the base class from within a derived class or invoke a base class constructor.

  • Example: public MyConstructor() : base() { }

delegate

  • Explanation: Declares a reference type that encapsulates a method with a specific signature, or creates an anonymous method.

  • Example: delegate void LogHandler(string msg);

dynamic

  • Explanation: Defines a type that bypasses compile-time type checking, resolving operations dynamically at runtime.

  • Example: dynamic obj = GetUnknownObject(); obj.DoSomething();

event

  • Explanation: Declares a member that enables a class or object to provide notifications to other objects when something of interest occurs.

  • Example: public event Action OnClick;

explicit

  • Explanation: Declares a user-defined custom type conversion operator that must be invoked with a cast.

  • Example: public static explicit operator int(Digit d) => d.Value;

file

  • Explanation: Restricts a type's visibility solely to the source file in which it is declared.

  • Example: file class LocalHelper { }

get / set / init

  • Explanation: Defines accessors for reading, writing, or initializing a property/indexer.

  • Example: public int Id { get; init; }

global

  • Explanation: Refers to the default root namespace, preventing collision with custom namespaces of the same name.

  • Example: global::System.Console.WriteLine();

implicit

  • Explanation: Declares a user-defined custom type conversion operator that occurs automatically without an explicit cast.

  • Example: public static implicit operator double(Digit d) => d.Value;

lock

  • Explanation: Obtains a mutual-exclusion lock for a given object, executes a statement block, and then releases the lock safety.

  • Example: lock(syncLock) { SharedCount++; }

managed / unmanaged

  • Explanation: Specifies whether a pointer point context behaves as .NET garbage-collected data, or constrains a generic type to unmanaged structs.

  • Example: where T : unmanaged

namespace

  • Explanation: Declares a scope that contains a set of related objects, organizing code elements into a logical tree.

  • Example: namespace Enterprise.Core;

nint / nuint

  • Explanation: Represents native sized signed/unsigned integer types which match the platform pointer size at runtime.

  • Example: nint nativeAddress = 0;

null

  • Explanation: Represents a literal value that signifies a reference type variable does not point to any object instance in memory.

  • Example: string text = null;

operator

  • Explanation: Overloads built-in arithmetic or comparison operators to define custom operations for structures or classes.

  • Example: public static Vector operator +(Vector a, Vector b)

record

  • Explanation: Declares a reference or value type optimized for immutable data models with built-in value-based equality.

  • Example: public record Person(string Name, int Age);

ref fields / scoped

  • Explanation: Restricts variables or values to live only within the current stack frame, preventing heap escape.

  • Example: scoped ref int localRef = ref x;

required

  • Explanation: Specifies that a property or field must be initialized by an object initializer during creation.

  • Example: public required string Username { get; set; }

this

  • Explanation: Refers to the current instance of the class or struct and can also be used to define extension methods.

  • Example: this.name = name;

using

  • Explanation: Defines a scope at the end of which disposable resources are auto-released, or imports a namespace.

  • Example: using (var stream = new MemoryStream()) { }

value

  • Explanation: Contextual keyword used within property or indexer set/init accessors representing the value incoming from client code.

  • Example: set { _name = value; }

var

  • Explanation: Instructs the compiler to infer the precise type of a variable from its initialization expression.

  • Example: var message = "Hello";

with

  • Explanation: Creates a copy of a record or struct instance while modifying specified properties in the new object.

  • Example: var updated = original with { Age = 30 };

yield

  • Explanation: Used in an iterator block to signal returning a value sequentially to an enumerable loop consumer without terminating the iterator.

  • Example: yield return item;

Comments

Popular posts from this blog

Entity Framework: Database First Approach in .NET

Getting Started with Entity Framework: Database First Approach in .NET Entity Framework (EF) is a powerful Object-Relational Mapper (ORM) that allows developers to work with databases using C# objects instead of writing raw SQL queries. 🔷 What is Entity Framework? Entity Framework simplifies database interaction by mapping database tables to C# classes, enabling clean and maintainable code. +-------------------+ +---------------------+ +------------------+ | C# Classes | ----> | Entity Framework | ----> | Database | | (Entities) | | (ORM Layer) | | (Tables/Rows) | +-------------------+ +---------------------+ +------------------+ 🔷 Entities and Domain Classes 📌 Entity Classes Entity classes represent database tables. Each object corresponds to a row in the table. 📌 Domain Classes Domain classes represent business logic and real-world entities. Entities: Have primary keys Val...

Entity Framework: Code First Approach in .NET

  🚀 Entity Framework: Code First Approach in .NET Entity Framework (EF) is a powerful Object-Relational Mapper (ORM) that allows developers to work with databases using C# classes instead of raw SQL queries . 🔷 What is Entity Framework? As discussed in the previous blog, Entity Framework simplifies database interaction by mapping C# objects to database tables , enabling clean, maintainable, and strongly typed data access. +-------------------+ +---------------------+ +------------------+ | C# Classes | ----> | Entity Framework | ----> | Database | | (Entities) | | (ORM Layer) | | (Tables/Rows) | +-------------------+ +---------------------+ +------------------+ 🔷 Entities and Domain Classes 📌 Entity Classes Entity classes represent database tables . Each object represents a row. Example: public class Student { public int Id { get ; set ; } public string Name { get ; set ; }...