C# Programming Tutorial

Learn C# programming from the fundamentals to object-oriented programming and practical application development. This course covers variables, data types, operators, conditional statements, loops, methods, arrays, classes, objects, inheritance, polymorphism, exception handling and collections.

Programming Beginner to Intermediate 28 Lessons Practical Examples

1. What is C#?

C# (pronounced "C Sharp") is a modern, object-oriented programming language developed by Microsoft. It is commonly used for developing Windows applications, web applications, APIs, desktop software, games and enterprise applications.

C# works closely with the .NET platform. The .NET platform provides libraries, runtime services and tools that allow C# applications to execute and interact with operating systems, databases, networks and other technologies.

Where is C# Used?

  • Web application development
  • ASP.NET applications
  • REST APIs
  • Windows desktop applications
  • Enterprise software
  • Game development using Unity
  • Cloud applications
Important: C# is not limited to Windows. Modern .NET allows C# applications to run across Windows, Linux and macOS.

2. Features of C#

C# provides many features that make it suitable for modern software development.

Object-Oriented

C# supports object-oriented programming concepts such as classes, objects, inheritance, encapsulation and polymorphism.

Strongly Typed

C# requires variables to have a specific data type. The compiler checks many type-related errors before the program executes.

Type Safe

C# provides strong type checking which helps prevent invalid operations between incompatible data types.

Automatic Memory Management

C# uses garbage collection to automatically manage memory used by objects.

Rich Library Support

The .NET class libraries provide functionality for collections, files, networking, databases, security and many other operations.


3. C# and .NET

C# is a programming language, while .NET is a development platform that provides the runtime, libraries and tools required to build and execute applications.

Technology Purpose
C# Programming language used to write application logic.
.NET Platform containing runtime, libraries and development tools.
ASP.NET Framework for building web applications and web APIs using .NET.

4. First C# Program

Let's create a simple C# program that displays "Hello World" on the screen.

C# Program
using System;

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

Understanding the Program

  • using System; imports the System namespace.
  • class Program defines a class.
  • Main() is the entry point of the application.
  • Console.WriteLine() displays text on the console.

5. C# Variables

A variable is a named memory location used to store a value during program execution.

Unlike Python, C# is strongly typed. Therefore, a variable normally has a declared data type.

string name = "Rahul";

int age = 21;

double marks = 85.50;

bool isPassed = true;

Variable Declaration

The general syntax is:

dataType variableName = value;

Example

int number = 100;

Console.WriteLine(number);
Output
100

6. C# Data Types

A data type specifies the kind of value that a variable can store.

Data Type Example Purpose
int 100 Whole numbers
double 10.50 Decimal numbers
float 10.5f Single precision decimal
decimal 100.50m Financial calculations
char 'A' Single character
string "Hello" Text
bool true True or false

Example

int age = 25;

double salary = 45000.50;

char grade = 'A';

string name = "Student";

bool isActive = true;

7. Constants

A constant is a value that cannot be changed after it has been initialized.

const double PI = 3.14159;

Console.WriteLine(PI);
Important: A constant must be assigned a value when it is declared, and its value cannot be changed later.

8. Type Conversion

Type conversion means converting a value from one data type to another.

Implicit Conversion

A smaller compatible numeric type can generally be converted into a larger compatible numeric type automatically.

int number = 100;

double value = number;

Console.WriteLine(value);

Explicit Conversion

double value = 100.75;

int number = (int)value;

Console.WriteLine(number);
Output
100

9. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations.

int a = 10;

int b = 3;

Console.WriteLine(a + b);

Console.WriteLine(a - b);

Console.WriteLine(a * b);

Console.WriteLine(a / b);

Console.WriteLine(a % b);
Output
13 7 30 3 1
Note: When both operands are integers, integer division produces an integer result.

10. Comparison Operators

Comparison operators compare two values and return a Boolean result.

int a = 10;

int b = 20;

Console.WriteLine(a == b);

Console.WriteLine(a != b);

Console.WriteLine(a > b);

Console.WriteLine(a < b);

Console.WriteLine(a >= b);

Console.WriteLine(a <= b);

11. Logical Operators

Logical operators combine Boolean expressions.

int age = 25;

bool result1 = age >= 18 && age <= 60;

bool result2 = age < 18 || age > 60;

bool result3 = !(age > 18);

Console.WriteLine(result1);

Console.WriteLine(result2);

Console.WriteLine(result3);

12. Assignment Operators

int number = 10;

number += 5;

Console.WriteLine(number);

number -= 3;

Console.WriteLine(number);

number *= 2;

Console.WriteLine(number);
Output
15 12 24

13. if / else Statement

Conditional statements allow a program to execute different code depending on a condition.

int age = 20;

if (age >= 18)
{
    Console.WriteLine("Adult");
}
else
{
    Console.WriteLine("Minor");
}
Output
Adult

else-if

int marks = 75;

if (marks >= 90)
{
    Console.WriteLine("Grade A+");
}
else if (marks >= 75)
{
    Console.WriteLine("Grade A");
}
else if (marks >= 60)
{
    Console.WriteLine("Grade B");
}
else
{
    Console.WriteLine("Grade C");
}

14. switch Statement

The switch statement is useful when a program needs to compare one expression against multiple possible values.

int day = 2;

switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;

    case 2:
        Console.WriteLine("Tuesday");
        break;

    case 3:
        Console.WriteLine("Wednesday");
        break;

    default:
        Console.WriteLine("Invalid Day");
        break;
}
Output
Tuesday

15. for Loop

A for loop is used when a block of code needs to execute repeatedly for a known or controlled number of iterations.

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}
Output
1 2 3 4 5

16. while Loop

The while loop executes a block of code while a condition remains true.

int i = 1;

while (i <= 5)
{
    Console.WriteLine(i);

    i++;
}

17. break and continue

break

The break statement terminates the loop immediately.

for (int i = 1; i <= 10; i++)
{
    if (i == 5)
    {
        break;
    }

    Console.WriteLine(i);
}

continue

The continue statement skips the current iteration.

for (int i = 1; i <= 5; i++)
{
    if (i == 3)
    {
        continue;
    }

    Console.WriteLine(i);
}

18. Methods

A method is a reusable block of code that performs a specific task.

static void Greet()
{
    Console.WriteLine("Hello Student");
}

static void Main()
{
    Greet();
}
Output
Hello Student
Why use methods? Methods reduce code duplication and make large programs easier to organize and maintain.

19. Method Parameters

Parameters allow a method to receive values from the calling code.

static void Add(int a, int b)
{
    int result = a + b;

    Console.WriteLine(result);
}

static void Main()
{
    Add(10, 20);
}
Output
30

20. Return Values

A method can return a value using the return keyword.

static int Add(int a, int b)
{
    return a + b;
}

static void Main()
{
    int result = Add(10, 20);

    Console.WriteLine(result);
}
Output
30

21. Method Overloading

Method overloading allows multiple methods to have the same name but different parameter lists.

static int Add(int a, int b)
{
    return a + b;
}

static int Add(int a, int b, int c)
{
    return a + b + c;
}

static void Main()
{
    Console.WriteLine(Add(10, 20));

    Console.WriteLine(Add(10, 20, 30));
}
Output
30 60

22. Classes

A class is a blueprint or template used to create objects. It can contain fields, properties and methods.

class Student
{
    public string Name;

    public void Display()
    {
        Console.WriteLine(Name);
    }
}

23. Objects

An object is an instance of a class.

Student student = new Student();

student.Name = "Rahul";

student.Display();
Output
Rahul

24. Constructors

A constructor is a special method that is called automatically when an object is created.

class Student
{
    public string Name;

    public Student(string name)
    {
        Name = name;
    }

    public void Display()
    {
        Console.WriteLine(Name);
    }
}

Student student = new Student("Rahul");

student.Display();
Output
Rahul

25. Encapsulation

Encapsulation means combining data and methods inside a class while controlling how that data can be accessed.

class BankAccount
{
    private double balance;

    public void Deposit(double amount)
    {
        balance += amount;
    }

    public double GetBalance()
    {
        return balance;
    }
}

BankAccount account = new BankAccount();

account.Deposit(5000);

Console.WriteLine(account.GetBalance());
Output
5000
Key idea: The balance field is private, so outside code cannot directly modify it. Access is controlled through methods.

26. Inheritance

Inheritance allows a derived class to reuse members of a base class.

class Animal
{
    public void Eat()
    {
        Console.WriteLine("Animal is eating");
    }
}

class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Dog is barking");
    }
}

Dog dog = new Dog();

dog.Eat();

dog.Bark();
Output
Animal is eating Dog is barking

27. Polymorphism

Polymorphism allows the same method or interface to behave differently depending on the object.

class Animal
{
    public virtual void Sound()
    {
        Console.WriteLine("Animal sound");
    }
}

class Dog : Animal
{
    public override void Sound()
    {
        Console.WriteLine("Dog barks");
    }
}

Animal animal = new Dog();

animal.Sound();
Output
Dog barks

28. Arrays

An array stores multiple values of the same data type in a fixed-size collection.

int[] marks = { 80, 75, 90, 85 };

for (int i = 0; i < marks.Length; i++)
{
    Console.WriteLine(marks[i]);
}
Output
80 75 90 85

29. Collections

Collections provide flexible ways to store and manipulate groups of objects.

List

using System.Collections.Generic;

List<string> students = new List<string>();

students.Add("Amit");

students.Add("Rahul");

students.Add("Priya");

foreach (string student in students)
{
    Console.WriteLine(student);
}
Output
Amit Rahul Priya

30. Exception Handling

Exception handling allows a program to handle runtime errors gracefully.

try
{
    int a = 10;

    int b = 0;

    int result = a / b;

    Console.WriteLine(result);
}
catch (DivideByZeroException)
{
    Console.WriteLine("Cannot divide by zero.");
}
finally
{
    Console.WriteLine("Program completed.");
}
Output
Cannot divide by zero. Program completed.

Keywords

  • try contains code that may generate an exception.
  • catch handles the exception.
  • finally executes after the try/catch block.

31. File Handling

C# provides classes such as File and StreamReader for working with files.

Writing to a File

using System.IO;

File.WriteAllText(
    "student.txt",
    "Welcome to C# Programming"
);

Reading from a File

string content =
    File.ReadAllText("student.txt");

Console.WriteLine(content);
Output
Welcome to C# Programming

32. C# Mini Project

Student Result Calculator

Let's combine variables, arrays, loops, methods and conditional statements to create a simple student result calculator.

Complete C# Program
using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter Student Name: ");

        string name = Console.ReadLine();

        int[] marks = new int[3];

        int total = 0;

        for (int i = 0; i < 3; i++)
        {
            Console.Write("Enter marks: ");

            marks[i] = Convert.ToInt32(
                Console.ReadLine()
            );

            total += marks[i];
        }

        double percentage = total / 3.0;

        Console.WriteLine();
        Console.WriteLine("Student Name: " + name);
        Console.WriteLine("Total Marks: " + total);
        Console.WriteLine("Percentage: " + percentage);

        if (percentage >= 75)
        {
            Console.WriteLine("Grade: A");
        }
        else if (percentage >= 60)
        {
            Console.WriteLine("Grade: B");
        }
        else if (percentage >= 50)
        {
            Console.WriteLine("Grade: C");
        }
        else
        {
            Console.WriteLine("Grade: D");
        }
    }
}

Concepts Used

  • Variables
  • String input
  • Arrays
  • for loop
  • Arithmetic operations
  • Conditional statements
  • Type conversion
Practice Task: Modify this application so that it accepts five subjects and displays the student's name, total, percentage, grade and pass/fail status.

C# Course Summary

You have now covered the major fundamentals required to begin programming with C#. The next step is to practice each concept by building small applications.

Topics Covered

  • Introduction to C#
  • Features of C#
  • C# and .NET
  • Variables and Data Types
  • Constants and Type Conversion
  • Operators
  • Conditional Statements
  • Loops
  • Methods
  • Method Parameters and Return Values
  • Method Overloading
  • Classes and Objects
  • Constructors
  • Encapsulation
  • Inheritance
  • Polymorphism
  • Arrays
  • Collections
  • Exception Handling
  • File Handling
  • Mini Project
Recommended Practice: After completing this course, create a small Console Application such as a Student Management System, Calculator, Banking System, Quiz Application or Library Management System.