0 day streak
Code library

Beginner C# exercises

Read these Beginner C# snippets line by line — each one comes with a written breakdown of what the code does and why.

C# · Beginner

Defining Basic Methods

Methods are blocks of code that perform a specific task. They help organize code and make it reusable. 'void' means the method does not return a value.

SyntaxFunctions
Open snippet →
C# · Beginner

Introduction to Classes

A class is a blueprint for objects. In this example, the Book class defines what data a book has, and 'new Book()' creates an actual instance of it.

SyntaxOOP
Open snippet →
C# · Beginner

Working with Arrays

An array stores a fixed-size collection of elements of the same type. You access elements using an index, starting at 0.

SyntaxArrays & Lists
Open snippet →
C# · Beginner

Variables and Data Types

In C#, you must specify the type of data a variable will hold. Common types include string (text), int (whole numbers), and bool (true/false).

SyntaxData Types
Open snippet →
C# · Beginner

Conditional Logic with If-Else

The 'if' statement allows your program to make decisions. If the condition in parentheses is true, the first block of code runs; otherwise, the 'else' block runs.

SyntaxControl Flow
Open snippet →
C# · Beginner

The While Loop

A while loop repeatedly executes a block of code as long as a specified condition remains true. It is useful when the number of iterations is not known in advance.

Control FlowSyntax
Open snippet →
C# · Beginner

Basic Exception Handling

Try-catch blocks are used to handle errors (exceptions) gracefully. The code in the 'try' block runs, and if an error occurs, the 'catch' block handles it instead of crashing the program.

Error HandlingControl Flow
Open snippet →
C# · Beginner

Reading User Input

Console.ReadLine is used to pause program execution and wait for the user to type something into the terminal. The input is returned as a string.

Syntax
Open snippet →
C# · Beginner

Auto-Implemented Properties

Properties provide a flexible mechanism to read, write, or compute the value of a private field. Auto-properties simplify this by letting the compiler handle the private field for you.

OOPSyntax
Open snippet →
C# · Beginner

String Interpolation

String interpolation uses the '$' character to allow variables to be inserted directly into a string inside curly braces, making the code much more readable.

SyntaxData Types
Open snippet →
C# · Beginner

Asynchronous Task Basics

Asynchronous programming allows your application to remain responsive by offloading long-running operations. The 'async' modifier enables the 'await' keyword inside a method.

Async & ConcurrencyFunctions
Open snippet →
C# · Beginner

Safe Resource Disposal

The 'using' statement ensures that objects implementing IDisposable (like file streams) are properly closed and cleared from memory as soon as the block is finished.

Memory ManagementBest Practices
Open snippet →
C# · Beginner

Implementing a Single Instance

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. We use a private constructor to prevent outside instantiation.

Design PatternsOOP
Open snippet →
C# · Beginner

Fast String Construction

Strings in C# are immutable. For large-scale concatenation, using StringBuilder is much more efficient because it modifies a single internal buffer instead of creating many temporary strings.

PerformanceSyntax
Open snippet →
C# · Beginner

Preventing Invalid Data Input

Validating inputs is critical for security and stability. This check ensures that a string is not null, empty, or just whitespace before it is processed by the logic.

SecurityError Handling
Open snippet →
C# · Beginner

Async Method Execution

Asynchronous programming allows your code to wait for long-running operations like network requests or timers without freezing the entire application.

Async & Concurrency
Open snippet →
C# · Beginner

Using Statement Lifecycle

The 'using' statement is a best practice for managing memory with objects that implement IDisposable, ensuring resources like files or streams are closed automatically.

Memory ManagementBest Practices
Open snippet →
C# · Beginner

Enforcing Input Requirements

Validation logic at the start of a method (Guard Clauses) prevents invalid data from causing errors or security vulnerabilities deeper in your code.

SecurityBest Practices
Open snippet →
C# · Beginner

Asynchronous Delay Management

Async and await allow the program to handle long-running tasks without freezing the main thread. Task.Delay is a common way to simulate work asynchronously.

Async & ConcurrencySyntax
Open snippet →
C# · Beginner

Interface Contract Definition

Interfaces define a blueprint for classes. They allow for polymorphism and decouple the implementation from the usage, which is a key design pattern.

Design PatternsOOP
Open snippet →
C# · Beginner

Manual Truth Assertion

Testing ensures code reliability. In plain C#, you can create simple assertion methods to verify that your logic behaves as expected.

TestingError Handling
Open snippet →
C# · Beginner

Asynchronous Task Execution

Uses the async and await keywords to pause execution without blocking the main thread, which is essential for responsive applications.

Async & ConcurrencySyntax
Open snippet →
C# · Beginner

Asynchronous Method Handling

Async and await allow your program to perform tasks in the background without freezing the main execution flow, which is essential for responsive applications.

Async & ConcurrencyFunctions
Open snippet →
C# · Beginner

High-Efficiency Stack Storage

Using stackalloc manages memory on the stack instead of the heap, which is faster and reduces the work for the Garbage Collector in high-performance scenarios.

Memory ManagementPerformance
Open snippet →