C# Tutorial

This C# tutorial provides a structured path for learning C# programming, from variables, operators, conditions, and loops to object-oriented programming, exception handling, collections, file operations, and multithreading. Each topic focuses on the syntax and practical concepts used to build console, desktop, web, and service applications with .NET.

Getting Started with C# and .NET

C# is a statically typed, object-oriented programming language used with the .NET platform. Before working through the individual topics, install a recent .NET SDK and use an editor such as Visual Studio, Visual Studio Code, or another C#-compatible development environment.

Basic C# Program Structure

The following program displays a message in the terminal. It introduces a class, a Main method, and the Console.WriteLine() method.

</>
Copy
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, C#!");
    }
}
Hello, C#!

In newer C# project templates, the same program may use top-level statements and contain only Console.WriteLine("Hello, C#!");. Both forms are valid, depending on the project template and language version.

C# Console Input, Output, and Arguments

Console programs commonly read text from a user, display results, and accept values supplied when the application starts. These tutorials explain the main console APIs and command-line argument handling.

C# Variables, Data Types, and Operators

Variables store values that a program can read or modify. C# supports numeric types, characters, strings, Boolean values, arrays, classes, structures, enumerations, nullable types, and other specialized types.

  • C# Data Types
  • C# Type Inference with var
  • C# Type Conversion and Casting
  • C# Arithmetic Operators
  • C# Comparison Operators
  • C# Logical Operators
  • C# Assignment Operators
  • C# Nullable Value Types
</>
Copy
int quantity = 4;
double unitPrice = 12.50;
double total = quantity * unitPrice;

Console.WriteLine($"Total: {total}");
Total: 50

C# Conditional Statements and Decision Making

Conditional statements select which code should run based on Boolean expressions. Use if for general conditions and switch when one value must be compared against several cases.

  • C# if statement
  • C# if-else Statement
  • C# else-if Ladder
  • C# Nested if Statements
  • C# switch statement
  • C# Conditional Operator
</>
Copy
int score = 72;

if (score >= 60)
{
    Console.WriteLine("Passed");
}
else
{
    Console.WriteLine("Try again");
}

C# Loops and Loop Control Statements

Loops repeat a block of code. A for loop is useful when the number of repetitions is known, a while loop checks its condition before each iteration, and foreach processes elements from a collection.

C# Methods, Parameters, and Return Values

Methods organize reusable operations. A method can accept parameters, return a result, use optional or named arguments, and pass values with ref, out, or in when required.

  • C# Methods
  • C# Method Parameters
  • C# Return Values
  • C# Optional and Named Arguments
  • C# ref, out, and in Parameters
  • C# Local Functions
  • C# Lambda Expressions
</>
Copy
static int Add(int firstNumber, int secondNumber)
{
    return firstNumber + secondNumber;
}

int result = Add(10, 5);
Console.WriteLine(result);

C# Structures, Enumerations, and Value Types

Structures define value types that group related data and behavior. Enumerations provide readable names for a fixed set of integral constants.

  • C# Structure
  • C# Enum
  • C# Record Struct
  • C# Value Types and Reference Types

C# Classes and Object-Oriented Programming

Object-oriented C# programs use classes to combine state and behavior. The topics below cover object creation, constructors, inheritance, abstraction, interfaces, polymorphism, and method overloading.

  • C# Class
  • C# Objects
  • C# Constructors
  • C# Fields and Properties
  • C# Access Modifiers
  • C# Inheritance
  • C# Polymorphism
  • C# Abstract Classes and Methods
  • C# Interface
  • C# Method Overloading
  • C# Method Overriding
  • C# Static Members
  • C# Sealed Classes
  • C# Records

The following troubleshooting guide addresses a common constructor error encountered when creating objects:

C# Exception Handling and Common Exceptions

Exception handling lets a program respond to runtime failures without terminating unexpectedly. Use try for code that may fail, catch to handle an exception, and finally for cleanup that must run whether an exception occurs or not.

C# String Creation, Search, and Modification

A C# string is an immutable sequence of Unicode characters. String operations return a new string rather than modifying the original value. For repeated text construction, consider using StringBuilder.

  • C# String Length
  • C# Substring
  • C# Index of SubString
  • C# Replace String
  • C# Trim String
  • C# String Contains Substring
  • C# String StartsWith
  • C# String EndsWith
  • C# Join String Array
  • C# ToString
  • C# String Interpolation
  • C# Split String
  • C# Compare Strings
  • C# StringBuilder

C# Arrays, Lists, Dictionaries, and Collections

Collections store groups of values. Arrays have a fixed length, while generic collections such as List<T>, Dictionary<TKey, TValue>, HashSet<T>, Stack<T>, and Queue<T> support different access and storage patterns.

  • C# Array
  • C# List
  • C# SortedList
  • C# HashSet
  • C# SortedSet
  • C# Stack
  • C# Queue
  • C# LinkedList
  • C# Dictionary
  • C# SortedDictionary
  • C# IEnumerable and IEnumerator
  • C# Generic Collections

C# LINQ Queries for Collections

Language Integrated Query, commonly called LINQ, provides methods and query syntax for filtering, sorting, grouping, projecting, and aggregating data from collections and other data sources.

  • C# LINQ Where
  • C# LINQ Select
  • C# LINQ OrderBy and ThenBy
  • C# LINQ GroupBy
  • C# LINQ First, FirstOrDefault, and Single
  • C# LINQ Any and All
  • C# LINQ Count, Sum, Min, Max, and Average
</>
Copy
int[] numbers = { 4, 7, 10, 13, 16 };

IEnumerable<int> evenNumbers = numbers.Where(number => number % 2 == 0);

foreach (int number in evenNumbers)
{
    Console.WriteLine(number);
}
4
10
16

C# File and Directory Operations

The System.IO namespace provides APIs for reading and writing files, creating directories, copying paths, and deleting files or directory trees. Check whether a path exists and handle expected I/O exceptions when working with external storage.

C# Asynchronous Programming and Multithreading

C# supports concurrent and asynchronous work through threads, tasks, and the async/await syntax. Prefer task-based asynchronous APIs for non-blocking file, network, and database operations. Shared mutable data must be protected when multiple threads can access it.

  • C# Mutlithreading
  • C# Thread Class
  • C# Task and Task<TResult>
  • C# async and await
  • C# CancellationToken
  • C# lock Statement
  • C# Parallel Loops

C# Math Methods and Numeric Calculations

The System.Math class provides static methods for absolute values, rounding, powers, logarithms, trigonometry, minimum and maximum comparisons, and other numeric calculations.

Recommended C# Learning Order

Beginners can use the following order to avoid depending on concepts that have not yet been introduced:

  1. Create and run a basic C# console project.
  2. Learn variables, data types, conversions, and operators.
  3. Practice console input and formatted output.
  4. Use conditional statements and loops.
  5. Write reusable methods with parameters and return values.
  6. Study arrays, strings, lists, and dictionaries.
  7. Learn classes, objects, constructors, properties, and inheritance.
  8. Handle exceptions and perform file operations.
  9. Use LINQ to query collections.
  10. Continue with asynchronous programming, multithreading, and application-specific .NET frameworks.

C# Practice Checklist

  • Confirm that each example compiles with the .NET SDK version used for testing.
  • Check numeric conversions for truncation, overflow, and loss of precision.
  • Test every conditional branch, including boundary values.
  • Verify that loops terminate and do not skip required elements.
  • Handle null values before accessing object members.
  • Close or dispose files, streams, and other disposable resources.
  • Avoid modifying a collection while iterating over it unless the API explicitly supports that operation.
  • Use asynchronous APIs consistently instead of blocking with Wait() or Result in asynchronous code.

Frequently Asked Questions about Learning C#

Is C# suitable for beginners?

Yes. C# has explicit types, structured control flow, automatic memory management, and extensive .NET libraries. Beginners should first learn console programs before moving to larger application frameworks.

What is the difference between C# and .NET?

C# is a programming language. .NET is the development platform that provides the runtime, SDK, libraries, build tools, and application frameworks used to compile and run C# programs.

Which C# concepts should be learned first?

Start with variables, data types, operators, console input and output, conditional statements, loops, methods, arrays, and strings. Learn classes and other object-oriented concepts after these foundations are clear.

Should beginners learn LINQ before object-oriented programming?

Learn basic classes, methods, arrays, lists, and lambda expressions first. LINQ is easier to understand after you can create collections and pass functions as expressions.

How should C# examples be practiced?

Run each example, change its input values, predict the result before execution, and test boundary cases. Writing small programs that combine several concepts is more useful than reading syntax without compiling it.