C# logoC# INTERMEDIATE

C# Programming Language

Modern, object-oriented programming language for .NET platform with strong typing and automatic memory management

45 min read

Getting Started

Basic setup and first program

Hello World

Your first C# program

javascript
💡 Console.WriteLine adds a new line, Console.Write doesn't
⚡ Top-level programs (C# 9+) remove boilerplate
📌 $ before strings enables string interpolation
🟢 Console.ReadLine() always returns a string

Comments

Code documentation

javascript
💡 Use /// for IntelliSense documentation
⚡ Regions help organize large files
📌 TODO comments are tracked by Visual Studio
🟢 XML comments generate documentation files

Variables & Data Types

Basic data types and variable declarations

Basic Types

Common data types

javascript
💡 Use decimal for money to avoid rounding errors
⚡ int is the most common integer type
📌 Add f for float, m for decimal, L for long
🟢 string is for text, char is for single characters

Variable Declaration

Declaring and initializing variables

javascript
💡 Use var when type is obvious from right side
⚡ const for compile-time constants, readonly for runtime
📌 Variables are case-sensitive (age ≠ Age)
🟢 Follow C# naming conventions: camelCase for variables

Control Flow

Conditionals and loops

If Statements

Conditional execution

javascript
💡 Use && for AND, || for OR, ! for NOT
⚡ Ternary operator (? :) for simple if-else
📌 Always use braces {} even for single statements
🟢 Pattern matching makes type checking cleaner

Loops

Iteration and repetition

javascript
💡 Use foreach when you don't need the index
⚡ break exits loop, continue skips to next iteration
📌 While for unknown iterations, for when count is known
🟢 Do-while guarantees at least one execution

Methods (Functions)

Defining and calling methods

Method Basics

Creating and using methods

javascript
💡 void means method doesn't return a value
⚡ Static methods belong to class, instance methods to objects
📌 Method overloading allows same name with different parameters
🟢 Use => for single-expression methods

Parameters & Returns

Advanced parameter passing

javascript
💡 ref modifies original, out returns multiple values
⚡ params allows variable number of arguments
📌 in parameters for read-only reference passing
🟢 Tuples are great for returning multiple values

Basic Syntax

Fundamental C# syntax and structure

Hello World

Basic program structure

javascript
💡 C# 9.0+ supports top-level programs for simpler syntax
⚡ using statements import namespaces
📌 Main method is the entry point of the application
🟢 Console.WriteLine outputs text to console

Variables and Data Types

Variable declaration and common data types

javascript
💡 var keyword enables type inference at compile time
⚡ Nullable reference types help prevent null exceptions
📌 Value types are stored on stack, reference types on heap
🟢 Use specific types for better code clarity when needed

Object-Oriented Programming

Classes, objects, inheritance, and polymorphism

Classes and Objects

Defining classes and creating objects

javascript
💡 Auto-properties provide shorthand for simple get/set operations
⚡ Constructor initializes object state when created
📌 Access modifiers control visibility (public, private, protected)
🟢 Object initializer syntax allows setting properties during creation

Inheritance and Polymorphism

Class inheritance and method overriding

javascript
💡 Abstract classes cannot be instantiated directly
⚡ Virtual methods can be overridden in derived classes
📌 base keyword calls parent class constructor or methods
🟢 Polymorphism allows treating derived objects as base type

Collections and Generics

Working with collections and generic types

Generic Collections

List, Dictionary, and other generic collections

javascript
💡 Generic collections provide type safety and performance
⚡ Dictionary provides O(1) average lookup time
📌 HashSet automatically handles uniqueness of elements
🟢 Queue (FIFO) and Stack (LIFO) for specific ordering needs

LINQ and Lambda Expressions

Language Integrated Query and functional programming

LINQ Query Syntax

Querying collections with LINQ

javascript
💡 LINQ provides SQL-like querying for .NET collections
⚡ Method syntax often more flexible than query syntax
📌 Lambda expressions (=>) create anonymous functions
🟢 LINQ is lazy-evaluated until enumerated

Async/Await and Tasks

Asynchronous programming patterns

Basic Async/Await

Asynchronous methods and Task handling

javascript
💡 async/await makes asynchronous code look synchronous
⚡ Use Task.WhenAll for concurrent operations
📌 Avoid async void except for event handlers
🟢 ConfigureAwait(false) can improve performance in libraries

Exception Handling

Error handling and custom exceptions

Try-Catch-Finally

Basic exception handling patterns

javascript
💡 Catch specific exceptions before general ones
⚡ using statement ensures proper resource disposal
📌 finally block always executes, even after return
🟢 Exception filters allow conditional catch blocks

Interfaces and Abstract Classes

Contracts and abstract implementations

Interface Implementation

Creating and implementing interfaces

javascript
💡 Interfaces define contracts without implementation
⚡ C# 8+ allows default interface methods
📌 Classes can implement multiple interfaces
🟢 Use interfaces for dependency injection and testing

Delegates and Events

Function pointers and event-driven programming

Delegates and Func/Action

Working with delegates and built-in delegate types

javascript
💡 Delegates are type-safe function pointers
⚡ Action for void methods, Func for methods with return values
📌 Multicast delegates can call multiple methods
🟢 Events are special multicast delegates with restrictions

Properties and Indexers

Advanced property patterns and indexers

Property Patterns

Auto-properties, computed properties, and validation

javascript
💡 Init-only properties can only be set during object initialization
⚡ Computed properties recalculate on each access
📌 Property setters can include validation logic
🟢 Indexers allow array-like access to custom classes

Extension Methods and Nullable Types

Extending existing types and handling null values

Extension Methods

Adding methods to existing types

javascript
💡 Extension methods must be in static classes with static methods
⚡ First parameter with this keyword defines extended type
📌 Null-conditional operator (?.) safely accesses members
🟢 Nullable reference types help catch null issues at compile time

Attributes and Reflection

Metadata and runtime type inspection

Custom Attributes

Using and creating attributes for metadata

javascript
💡 Attributes add metadata to code elements
⚡ Reflection allows runtime type inspection and manipulation
📌 Custom attributes enable declarative programming
🟢 Use reflection sparingly as it impacts performance

Pattern Matching

Advanced pattern matching and switch expressions

Switch Expressions

Modern pattern matching with switch expressions

javascript
💡 Switch expressions provide concise pattern matching
⚡ Property patterns match on object properties
📌 Guard clauses (when) add additional conditions
🟢 List patterns enable array/collection matching

Records and Value Types

Modern data types and value semantics

Record Types

Immutable reference types with value semantics

javascript
💡 Records provide value equality and immutability by default
⚡ with expressions create copies with modified properties
📌 Records automatically implement ToString, Equals, GetHashCode
🟢 Use readonly structs for better performance

Memory Management

Memory optimization and performance considerations

IDisposable and Using

Resource management and deterministic cleanup

javascript
💡 IDisposable pattern ensures deterministic resource cleanup
⚡ Span<T> enables zero-allocation array operations
📌 ArrayPool reduces garbage collection pressure
🟢 Using declarations simplify resource management

Latest C# Features

Modern C# features and syntax improvements

C# 10-12 Features

Latest language enhancements and syntax improvements

javascript
💡 Global using reduces repetitive using statements
⚡ Raw string literals handle multi-line strings elegantly
📌 Required members ensure proper object initialization
🟢 Collection expressions provide concise initialization