Using C# 12 with Clean Code Practices

Overview

It is imperative to write clean, maintainable code in modern software development. Clean code practices improve readability, maintainability, collaboration, and debugging. Using C# 12, developers can further support clean code practices thanks to new language features and enhancements. Using C# 12 will allow us to write cleaner, more efficient code, and provide practical code examples.

What is the Clean Code?

The principles and practices of clean code promote clarity, simplicity, and efficiency. It adheres to the following principles:

  • Readability: Code should be easy to read and understand.
  • Simplicity: Keep code simple and avoid unnecessary complexity.
  • Consistency: Follow consistent coding conventions and patterns.
  • Modularity: Break down code into small, manageable pieces.

Enhancements in C# 12

C# 12 introduces several features that can help developers write clean code. These include:

  1. Primary Constructors
  2. Improved Pattern Matching
  3. Collection Literals
  4. Lambda Expression Improvements

Let’s explore these features with practical examples.

Primary Constructors

Using primary constructors simplifies initializing class members by allowing you to specify constructor parameters directly in the class declaration.

Before Primary Constructors

CleanCodePractices.Before.Person.cs

namespace CleanCodePractices.Before;

public class Person
{
    public string Name { get; }
    public int Age { get; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

With Primary Constructors

CleanCodePractices.After.Person.cs

namespace CleanCodePractices.After;
public class Person(string name, int age)
{
    public string Name { get; } = name;
    public int Age { get; } = age;
}

As a result, the class definition is more concise and requires less verbose constructor code.

Improved Pattern Matching

As a result of C# 12's improved pattern matching capabilities, such as not, or, and patterns, conditional logic is more expressive and readable.

Before Improved Pattern Matching

CleanCodePractices.Before.GetMessage.cs

namespace CleanCodePractices.Before;
public class Message
{
    public string GetMessage(object obj)
{
    if (obj is string str)
    {
        return $"String: {str}";
    }
    if (obj is int number)
    {
        return $"Number: {number}";
    }
    return "Unknown type";
}

}

With Improved Pattern Matching

CleanCodePractices.After.Message.cs

namespace CleanCodePractices.After;
public class Message
{
    public string GetMessage(object obj) => obj switch
    {
        string str => $"String: {str}",
        int number => $"Number: {number}",
        _ => "Unknown type"
    };


}

By using the switch expression, the code becomes more compact and readable.

Collection Literals

Using collection literals simplifies the creation of collections by eliminating the need for explicit initialization.

Before Collection Literals

//Before
var numbers = new List<int> { 1, 2, 3, 4, 5 };

foreach (var number in numbers)
{
    Console.WriteLine(number);
}

With Collection Literals

List<int>  numbersList = [1, 2, 3, 4, 5];



foreach (var numberList in numbersList)
{
    Console.WriteLine(numberList);
}

Collection initialization is now cleaner and more intuitive with this new syntax.

Lambda Expression Improvements

The C# 12 framework introduces enhancements to lambda expressions, including the ability to use lambda expressions with attributes and improve their usability.

Before Lambda Expression Improvements

Func<int, int> square = q => q * q;

With Lambda Expression Improvements

CleanCodePractices.After.MyCustomAttribute.cs

namespace CleanCodePractices.After;
// Define a custom attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
    public string Description { get; }

    public MyCustomAttribute(string description = "Custom attribute description")
    {
        Description = description;
    }
}

CleanCodePractices.After.Shape.cs

namespace CleanCodePractices.After;

public static class Shape
{
    // Apply the custom attribute to a method
    [MyCustomAttribute("We are using Custom Attribute Now")]
    public static int Square(int x)
    {
        return x * x;
    }
}

Program.cs

//After
int numberZ= 5;
int result = Shape.Square(numberZ);

// Display the result
Console.WriteLine($"The square of {numberZ} is {result}");

The addition of attributes to lambda expressions allows for greater flexibility and integration with other features.

Applying Clean Code Practices with C# 12

Using C# 12 features, here are some tips for applying clean code practices:

  • Use Primary Constructors to Reduce Boilerplate: By simplifying and clarifying complex conditional logic, you make your code easier to read and maintain.
  • Leverage Improved Pattern Matching for Clarity: Use enhanced pattern matching to simplify and clarify complex conditional logic. This makes your code easier to read and maintain.
  • Simplify Collection Initialization with Literals: By using collection literals, you can make your code cleaner and more expressive, resulting in less verbosity and better readability.
  • Enhance Lambda Expressions with Attributes: The use of lambda expression improvements can help you add metadata to your code, which can be particularly useful in scenarios involving dependency injection or custom attributes.

Summary

 With C# 12, you can write readable, maintainable, and efficient code with several features that support clean code practices. Developers can write clean code by leveraging primary constructors, improved pattern matching, collection literals, and lambda expression enhancements. Build robust, scalable applications with these features to enhance your development workflow.

I have uploaded the source code for this article please visit my GitHub repository and I truly value your support if you can like this article and also follow me on LinkedIn thanks in advance.


Similar Articles
Capgemini
Capgemini is a global leader in consulting, technology services, and digital transformation.