C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Switch Statement

The switch statement in C# is a control flow statement that allows you to perform different actions based on the value of a variable or an expression. It is a useful alternative to a series of if-else statements, especially when dealing with multiple possible values. In this tutorial, we'll cover the basics of working with switch statements in C#.

  • Basic switch statement

The switch statement works by evaluating an expression and comparing its value against different cases. If a match is found, the code block associated with that case is executed. The break statement is used to exit the switch block.

int number = 3;

switch (number)
{
    case 1:
        Console.WriteLine("One");
        break;
    case 2:
        Console.WriteLine("Two");
        break;
    case 3:
        Console.WriteLine("Three");
        break;
    default:
        Console.WriteLine("Unknown number");
        break;
}
  • Default case

The default case is optional and used when no other case matches the value of the expression. It is typically placed at the end of the switch block.

int number = 10;

switch (number)
{
    case 1:
        Console.WriteLine("One");
        break;
    case 2:
        Console.WriteLine("Two");
        break;
    default:
        Console.WriteLine("Unknown number");
        break;
}
  • Case fall-through

C# does not allow case fall-through by default, which means that you must use the break statement to exit the switch block after each case. However, you can use the goto case statement to jump to another case, or the goto default statement to jump to the default case.

int number = 1;

switch (number)
{
    case 1:
    case 2:
        Console.WriteLine("One or Two");
        break;
    case 3:
        Console.WriteLine("Three");
        break;
    default:
        Console.WriteLine("Unknown number");
        break;
}
  • Pattern matching

Starting with C# 7.0, the switch statement supports pattern matching, which allows you to match cases based on the type, value, or properties of an object.

object shape = new Circle { Radius = 5 };

switch (shape)
{
    case Circle c when c.Radius > 0:
        Console.WriteLine($"Circle with radius {c.Radius}");
        break;
    case Rectangle r when r.Width > 0 && r.Height > 0:
        Console.WriteLine($"Rectangle with dimensions {r.Width}x{r.Height}");
        break;
    case null:
        Console.WriteLine("Shape is null");
        break;
    default:
        Console.WriteLine("Unknown shape");
        break;
}
  • Switch expression (C# 8.0+)

C# 8.0 introduces the switch expression, which is a more concise alternative to the switch statement. It returns a value based on the matched case and uses the => symbol to separate the case from the expression.

int number = 3;

string word = number switch
{
    1 => "One",
    2 => "Two",
    3 => "Three",
    _ => "Unknown number"
};

Console.WriteLine(word);

In this tutorial, we covered the basics of working with switch statements in C#. The switch statement allows you to perform different actions based on the value of a variable or an expression, and it is a useful alternative to a series of if-else statements.

  1. How to use structs in C#

    Structs in C# are lightweight data types that represent a simple aggregate of data.

    public struct Point
    {
        public int X;
        public int Y;
    }
    
    Point origin = new Point();
    origin.X = 0;
    origin.Y = 0;
    
  2. Structs vs. classes in C#

    Structs and classes are both used to define custom types, but they differ in how they handle memory and data.

    // Struct example
    public struct Point { public int X; public int Y; }
    
    // Class example
    public class PointClass { public int X; public int Y; }
    
  3. Defining and declaring structs in C#

    Define a struct using the struct keyword and declare instances like other variables.

    public struct Book
    {
        public string Title;
        public string Author;
    }
    
    Book myBook;
    
  4. Structs and value types in C#

    Structs are value types, meaning they are stored directly where they are declared, not in a separate heap memory.

    struct Temperature
    {
        public double Celsius;
    }
    
    Temperature summerTemp;
    summerTemp.Celsius = 30.0;
    
  5. When to use structs vs. classes in C#

    Use structs for small, lightweight, and frequently copied data. Classes are suitable for more complex scenarios.

    // Struct example
    struct Point { public int X; public int Y; }
    
    // Class example
    class PointClass { public int X; public int Y; }
    
  6. Structs and memory allocation in C#

    Structs are typically allocated on the stack, providing better performance for small data structures.

    struct Measurement
    {
        public double Value;
        public string Unit;
    }
    
    Measurement weight;
    
  7. Nested structs in C#

    Structs can be nested within other structs or classes for better organization.

    struct Address
    {
        public string Street;
        public string City;
    
        public struct Coordinates
        {
            public double Latitude;
            public double Longitude;
        }
    }
    
  8. Initializing and working with structs in C#

    Initialize a struct using the default constructor or parameterized constructor.

    struct Point
    {
        public int X;
        public int Y;
    
        public Point(int x, int y)
        {
            X = x;
            Y = y;
        }
    }
    
    Point p = new Point(5, 10);
    
  9. Structs and immutability in C#

    Structs are inherently immutable if their fields are readonly.

    public readonly struct ImmutableStruct
    {
        public readonly int Value;
    
        public ImmutableStruct(int value)
        {
            Value = value;
        }
    }
    
  10. Copying and passing structs in C#

    Structs are copied by value, and passing them to methods involves passing a copy.

    struct Person
    {
        public string Name;
        public int Age;
    }
    
    void ModifyPerson(Person person)
    {
        person.Age = 30; // Does not modify the original struct
    }
    
  11. Structs and the heap vs. stack in C#

    Structs are often allocated on the stack, providing better performance compared to classes that are allocated on the heap.

    struct Point { public int X; public int Y; }
    Point stackPoint = new Point();
    
  12. Structs and interfaces in C#

    Structs can implement interfaces, allowing them to define a contract for behaviors.

    public interface IDrawable
    {
        void Draw();
    }
    
    public struct Circle : IDrawable
    {
        public void Draw()
        {
            // Implementation
        }
    }