Understanding the Optimal Use Cases for C# Primary Constructors
Published: 2023-12-09 19:44:00

C# 12 has brought an exciting new feature to the table: Primary Constructors. This addition simplifies the way we initialize and manage class properties, making our code more concise and readable. While primary constructors echo some aspects of record types, their application in classes opens up new possibilities.

## Understanding Primary Constructors
Primary Constructors allow the declaration of parameters directly in the class signature, making these parameters accessible throughout the class. This is particularly beneficial for initializing class properties.

Let’s craft a full blog post incorporating the revised eShop example with the primary constructors in C# 12.

## eShop Example: The Product Class
To understand the practical application, consider an eShop where products are a fundamental entity. Here’s how a Product class can leverage primary constructors.

```
public class Product(string name, decimal price)
{
    public string Name { get; private set; } = name;
    public decimal Price { get; private set; } = price;

    public void ApplyDiscount(decimal discountPercentage)
    {
        if (discountPercentage < 0 || discountPercentage > 100)
        {
            throw new ArgumentOutOfRangeException(nameof(discountPercentage), "Discount percentage must be between 0 and 100.");
        }

        Price -= Price * (discountPercentage / 100);
    }
}
```

In this example, the Product class initializes Name and Price using primary constructors. The ApplyDiscount method demonstrates a real-world use case, modifying the Price based on a discount percentage.

## Advantages in eShop Context
This approach simplifies class design and makes it more intuitive to understand and use. For instance, in an e-commerce application, being able to quickly define and manipulate product-related data is crucial for rapidly evolving product catalogs and pricing strategies.

## Scope and Validation
One of the initial questions that arise with primary constructors is about the scope of the parameters. These parameters are accessible throughout the class, similar to regular constructor parameters. However, they should be used judiciously, especially when it comes to validation and manipulation.

In our Product class, we validate the discountPercentage in the ApplyDiscount method, ensuring robustness in our class design.

## Dependency Injection and Beyond
Primary constructors work seamlessly with dependency injection, further enhancing their utility in modern .NET applications. They can simplify the injection of services and dependencies, a common pattern in e-commerce platforms where services like pricing algorithms, inventory management, and customer data handling are crucial.

## Conclusion
Primary Constructors in C# 12 offers a streamlined, efficient approach to initializing and managing class properties, particularly beneficial in e-commerce applications like eShops. By understanding and applying these constructors effectively, developers can write cleaner, more maintainable code, contributing to the robustness and scalability of their applications.

Remember, while primary constructors offer great power, they come with the responsibility of careful use, especially in maintaining the integrity and validation of the data they handle.

Cheers👋

---

Follow me on LinkedIn: www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&followMember=admir-live