Categories C#

Switch Statement vs Switch Expression C#

C# 8.0 introduced Switch Expression. A shortened version of the switch and evaluate a single expression. You can apply Pattern Matching.

Switch Statement

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(GetGender(Gender.Male).ToString());
        Console.ReadLine();
    }

    public enum Gender
    {
        Male,
        Female,
        Transgender
    }

    public static string GetGender(Gender gender)
    {
        string sGender = string.Empty;

        switch (gender)
        {
            case Gender.Male: sGender = "Male"; break;
            case Gender.Female: sGender = "Female"; break;
            case Gender.Transgender: sGender = "Transgender"; break;
            default: break;
        }

        return sGender;
    }
}
C#

Switch Expression

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
        Console.WriteLine(GetGender(Gender.Male));
    }

    public enum Gender
    {
        Male,
        Female,
        Transgender
    }

    public static string GetGender(Gender gender) => gender switch
    {
        Gender.Male => "Male",
        Gender.Female => "Female",
        Gender.Transgender => "Transgender",
        _ => ""
    };
}
C#

Written By

With over a decade of experience in .NET technologies, SQL Server, and Agile methodologies, I am a Lead Software Developer at TEKsystems, where I design, develop, and support web-based applications for a leading market research company. I hold multiple certifications in LINQ, Entity Framework, and other .NET frameworks and tools, demonstrating my proficiency and commitment to continuous learning.

My core competencies include .NET Core, User Defined Functions, Stored Procedures, MVC, Web API, jQuery, and Bootstrap. I have successfully delivered several projects, such as a dashboard for analyzing consumer behavior, a portal for managing surveys and reports, and a tool for automating data quality checks. I am passionate about creating innovative and user-friendly solutions that help clients make informed business decisions. As part of a collaborative and agile team, I contribute to improving the quality, performance, and security of web applications, as well as providing technical support and documentation.

Email: codewithsivablog@gmail.com

More From Author

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like