C# Basics

Table of Contents

Getting Started

First C# Program:


// Basic program structure
using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
            
            // Reading input
            Console.Write("Enter your name: ");
            string name = Console.ReadLine();
            
            // String interpolation
            Console.WriteLine($"Welcome, {name}!");
        }
    }
}
        

Data Types and Variables


// Value Types
int number = 42;
double price = 19.99;
bool isValid = true;
char grade = 'A';

// Reference Types
string name = "John";
object obj = new object();

// Nullable Types
int? nullableNumber = null;
bool? nullableBool = null;

// Constants
const double PI = 3.14159;

// Implicit Typing
var age = 25;      // Type is inferred as int
var text = "Hello"; // Type is inferred as string
    

Operators

Common Operators:


// Arithmetic Operators
int sum = 5 + 3;      // Addition
int diff = 10 - 4;    // Subtraction
int product = 6 * 2;  // Multiplication
int quotient = 15 / 3;// Division
int remainder = 7 % 2; // Modulus

// Comparison Operators
bool isEqual = (5 == 5);     // Equal to
bool isNotEqual = (5 != 3);  // Not equal to
bool isGreater = (7 > 3);    // Greater than
bool isLessEqual = (4 <= 4); // Less than or equal to

// Logical Operators
bool and = true && false;  // Logical AND
bool or = true || false;   // Logical OR
bool not = !true;         // Logical NOT

// Assignment Operators
int x = 10;
x += 5;  // x = x + 5
x -= 3;  // x = x - 3
x *= 2;  // x = x * 2
x /= 4;  // x = x / 4
        

Control Flow

If Statements


if (age >= 18)
{
    Console.WriteLine("You are an adult");
}
else if (age >= 13)
{
    Console.WriteLine("You are a teenager");
}
else
{
    Console.WriteLine("You are a child");
}

// Ternary operator
string status = (age >= 18) ? "Adult" : "Minor";
    

Loops


// For Loop
for (int i = 0; i < 5; i++)
{
    Console.WriteLine($"Iteration {i}");
}

// While Loop
int count = 0;
while (count < 3)
{
    Console.WriteLine($"Count: {count}");
    count++;
}

// Do-While Loop
int number;
do
{
    Console.Write("Enter a number (1-10): ");
    number = int.Parse(Console.ReadLine());
} while (number < 1 || number > 10);

// Foreach Loop
string[] fruits = { "apple", "banana", "orange" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
    

Arrays and Collections

Arrays:


// Single-dimensional array
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;

// Array initialization
string[] colors = { "red", "green", "blue" };

// Multi-dimensional array
int[,] matrix = new int[3,3];
matrix[0,0] = 1;
matrix[0,1] = 2;

// Jagged array
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
        

Collections


// List
List<string> names = new List<string>();
names.Add("John");
names.Add("Jane");

// Dictionary
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["John"] = 25;
ages["Jane"] = 30;

// HashSet
HashSet<int> uniqueNumbers = new HashSet<int>();
uniqueNumbers.Add(1);
uniqueNumbers.Add(2);
    

Methods


// Basic method
public void Greet(string name)
{
    Console.WriteLine($"Hello, {name}!");
}

// Method with return value
public int Add(int a, int b)
{
    return a + b;
}

// Method with optional parameters
public void Print(string message, bool uppercase = false)
{
    if (uppercase)
        Console.WriteLine(message.ToUpper());
    else
        Console.WriteLine(message);
}

// Method with out parameter
public bool TryParse(string input, out int result)
{
    return int.TryParse(input, out result);
}
    

Classes and Objects

Basic Class Structure:


public class Person
{
    // Fields
    private string _name;
    private int _age;

    // Properties
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    // Auto-implemented property
    public int Age { get; set; }

    // Constructor
    public Person(string name, int age)
    {
        _name = name;
        _age = age;
    }

    // Method
    public void Introduce()
    {
        Console.WriteLine($"Hi, I'm {_name} and I'm {_age} years old.");
    }
}

// Using the class
Person person = new Person("John", 25);
person.Introduce();
        

Common Patterns

Error Handling:


try
{
    int result = 10 / 0; // This will throw an exception
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero!");
    Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("An error occurred!");
    Console.WriteLine(ex.Message);
}
finally
{
    Console.WriteLine("This always executes");
}
        

Related Resources