Master Every Keyword, Classic and New, With Examples, Explanations, and Best Practices
Understanding keywords is fundamental to becoming a confident C# developer. Keywords define the language’s syntax, behavior, and capabilities. They govern how you declare types, control flow, handle memory, and work with modern .NET 10 features in C# 14.
This guide covers all keywords – classic, contextual, and the new additions in C# 14, with examples, usage patterns, and practical tips.
🔍 The Problem: Developers Often Misunderstand Keywords
Even experienced C# developers sometimes misuse or overlook keywords:
varmisuse – assuming it’s weak typing when it’s just implicit typing.field– many don’t know it replaces backing fields for auto-properties.- Extension member keywords – C# 14 allows static extension properties and methods, but many miss their potential.
- Confusing classic and contextual keywords, especially in LINQ, async, and pattern matching.
Misunderstanding keywords leads to:
- Verbose or redundant code
- Runtime errors due to improper type handling
- Poor readability and maintainability
⚡ The Solution: A Full Keyword Reference for .NET 10 / C# 14
C# has 79+ keywords, some of which are contextual, meaning they only have special meaning in certain contexts. In C# 14, several new keywords and behaviors were added.
I’ll break them into practical categories with explanations, examples, and modern usage tips.
🧠 Data Types & Type Keywords
These define fundamental types and structures:
| Keyword | Meaning | Example |
|---|---|---|
int | 32-bit signed integer | int count = 42; |
long | 64-bit signed integer | long big = 1234567890L; |
float, double, decimal | Floating-point / precise decimal | decimal price = 19.99m; |
bool | True/false | bool isValid = true; |
char | Single character | char letter = 'A'; |
string | Immutable text | string name = "James"; |
object | Base type | object obj = new(); |
dynamic | Runtime type | dynamic dyn = "Hello"; dyn = 5; |
var | Implicitly typed | var x = 123; |
struct | Value type | struct Point { public int X, Y; } |
class | Reference type | class Person { public string Name; } |
record | Immutable or value-like class | record Person(string Name, int Age); |
enum | Named constants | enum Day { Mon, Tue, Wed }; |
Pro tip: Use var and record in modern .NET 10 code for cleaner, concise, and immutable designs.
🧩 Declaration & Constant Keywords
| Keyword | Meaning | Example |
|---|---|---|
const | Compile-time constant | const double Pi = 3.14159; |
readonly | Runtime constant (constructor-only) | readonly string Id; |
new | Instantiate object / hide members | var person = new Person(); |
default | Default value of type | int n = default; // 0 |
Modern C# 14 tip: Use field instead of manual backing fields:
public string Name
{
get;
set => field = value ?? throw new ArgumentNullException(nameof(value));
}
🧭 Flow Control Keywords
| Keyword | Purpose | Example |
|---|---|---|
if / else | Conditional branching | if (x > 0) { ... } else { ... } |
switch / case / default | Multi-way branching | switch(value) { case 1: ... break; default: ... } |
for, foreach | Loops | foreach(var item in list) { ... } |
while, do | Conditional loops | while(flag) { ... } |
break, continue | Loop control | if(x>10) break; |
goto | Jump to label | goto Label; Label: ... |
return | Exit method / return value | return result; |
Pro tip: Prefer switch expressions in modern C# 14 for concise pattern matching:
string dayType = day switch
{
Day.Sat or Day.Sun => "Weekend",
_ => "Weekday"
};
🛡 Exception Handling Keywords
| Keyword | Use | Example |
|---|---|---|
try | Block that may throw | try { ... } |
catch | Handle exceptions | catch(Exception ex) { ... } |
finally | Always executed | finally { Cleanup(); } |
throw | Raise exception | throw new InvalidOperationException(); |
🏗 Object-Oriented Programming Keywords
| Keyword | Meaning | Example |
|---|---|---|
class | Reference type | class Car { ... } |
struct | Value type | struct Point { ... } |
record | Immutable data type | record Person(string Name, int Age); |
interface | Contract definition | interface IWorker { void Work(); } |
abstract | Must be overridden | abstract class Animal { abstract void Speak(); } |
virtual | Allow override | public virtual void Start() { } |
override | Override base method | public override void Start() { ... } |
sealed | Prevent inheritance | sealed class FinalClass { } |
this | Reference current instance | this.Value = value; |
base | Access base class member | base.ToString(); |
🧱 Access Modifiers & Member Keywords
| Keyword | Purpose | Example |
|---|---|---|
public, private, protected, internal | Access levels | public int Id; |
protected internal, private protected | Mixed visibility | protected internal void Method() { } |
static | Class-level member | public static void Log() { } |
volatile | Multithread-safe field | private volatile bool _flag; |
readonly | Assignable once | readonly int Value; |
⚡ Methods, Parameters & Return
| Keyword | Use | Example |
|---|---|---|
void | No return value | void DoSomething() { ... } |
return | Return a value | return x + y; |
params | Variable number of args | void Print(params string[] lines) { ... } |
ref | Pass by reference | void Increment(ref int x) { x++; } |
out | Output parameter | bool TryGet(out int value) { ... } |
in | Read-only reference | void Do(in Point p) { ... } |
🔬 Memory & Performance Keywords
| Keyword | Purpose | Example |
|---|---|---|
unsafe | Allow pointers | unsafe { int* ptr = &x; } |
fixed | Pin memory | fixed(int* ptr = arr) { ... } |
stackalloc | Stack allocation | Span<int> arr = stackalloc int[10]; |
C# 14 Enhancement: Implicit Span<T> and ReadOnlySpan<T> conversions reduce boilerplate for high-performance code:
int[] data = { 1, 2, 3 };
Span<int> span = data;
ReadOnlySpan<int> ro = data;
🎯 Functional / LINQ Keywords
| Keyword | Use | Example |
|---|---|---|
from | Start LINQ query | from x in list |
select | Project value | select x*2 |
where | Filter results | where x>10 |
group | Group by key | group p by p.Category |
join / into | Join collections | join c in cities on p.City equals c.Name into g |
orderby | Sort results | orderby x descending |
let | Store intermediate | let sq = x*x |
⏱ Async & Iterators
| Keyword | Purpose | Example |
|---|---|---|
async | Mark async method | async Task Load() |
await | Await a Task | await Task.Delay(500); |
yield | Iterator block | yield return item; |
🌟 New & Contextual Keywords in C# 14
| Feature | Keyword | Explanation |
|---|---|---|
| Extension members | extension | Static extension properties/methods in an extension block. |
| Backing field | field | Use inside property setters to reference the compiler-generated backing field. New in C# 14 .NET 10 |
| Null-conditional assignment | ?. (left-hand) | Assign only if target is not null. |
| Lambda parameter modifiers | ref, in, out | Use inside lambdas with modified parameters. |
| Partial constructors / events | partial | Define constructors and events in separate partial class files. |
| Implicit Span conversions | — | Array → Span<T> / ReadOnlySpan<T> conversion. |
| User-defined compound assignments | +=, -= | Custom operators for user types. |
🧰 Miscellaneous Keywords
| Keyword | Use | Example |
|---|---|---|
is | Type checking / pattern matching | if(obj is string s) ... |
as | Safe cast | var s = obj as string; |
sizeof | Size of value type | int size = sizeof(int); |
typeof | Type object | Type t = typeof(List<>); |
lock | Thread synchronization | lock(_sync) { ... } |
checked / unchecked | Numeric overflow control | checked { int x = int.MaxValue + 1; } |
null | Null literal | string s = null; |
true / false | Boolean literals | bool flag = true; |
🧩 Real-World Examples of New C# 14 Keywords
Backing Field Example
public string Name
{
get;
set => field = value ?? throw new ArgumentNullException(nameof(value));
}
Extension Members Example
public static class MyExtensions
{
extension<T>(IEnumerable<T> source)
{
public bool IsEmpty => !source.Any();
public int CountOrZero => source?.Count() ?? 0;
}
}
Implicit Span Conversion
int[] numbers = {1,2,3,4};
Span<int> span = numbers;
ReadOnlySpan<int> readOnly = numbers;
Null-Conditional Assignment
employee?.DepartmentId = GetDepartmentId(empId);
🧠 Best Practices for Keywords in .NET 10 / C# 14
✅ Use var for clarity with obvious types.
✅ Prefer record for immutable data objects.
✅ Use field in properties to simplify code.
✅ Leverage new extension members for reusable utilities.
✅ Adopt implicit Span conversions for high-performance scenarios.
✅ Prefer modern switch expressions with pattern matching.
✅ Use async/await consistently for asynchronous code.
Summary
| Concept | Old C# | C# 14 / .NET 10 |
|---|---|---|
| Property Backing | Manual field | field contextual keyword |
| Extension Members | Only methods | Static properties, methods, operators |
| Memory Safety | Manual Span conversion | Implicit Span<T> / ReadOnlySpan<T> |
| Lambda Parameters | Limited | ref, in, out allowed |
| Switch | Verbose | Switch expressions & patterns |
| Compound Assignment | Limited | User-defined +=, -= |
| Async | Basic | Full pattern with await & pipelines |
Mastering keywords in C# 14 means understanding classic syntax, modern enhancements, and new productivity patterns. With this guide, you can confidently write modern, maintainable, and high-performance C# code in .NET 10.