DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Tip: Data Members in Interfaces

Let’s talk about Data Members in Interfaces, introduced in C# 12, which allow you to define data members directly inside interfaces, making them more powerful and flexible. See the example in the code below.

public interface IProduct
{
    string Name { get; set; }
    decimal Price { get; set; }

    // Data member with default value
    decimal Tax => 0.15m;

    decimal CalculatePriceWithTax() => Price + (Price * Tax);
}

public class Product : IProduct
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class Program
{
    public static void Main()
    {
        IProduct product = new Product { Name = "Pen", Price = 10.00m };
        Console.WriteLine($"Product: {product.Name}, Price with tax: {product.CalculatePriceWithTax():C}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

In C# 12, you can declare data members directly within interfaces. This means that, in addition to abstract methods and properties, an interface can now have concrete data fields, offering a way to share state or default values among implementations. This new feature allows interfaces to serve not only as behavior contracts but also as containers for shared data between their implementations.

This is useful in scenarios where multiple classes share the same set of data but still need to implement specific behaviors. With this approach, your code becomes more organized, as interfaces can provide both behavior and default data for their implementations.

Source code: GitHub

I hope this tip helps you use Data Members in Interfaces to better organize your code! Until next time.

Top comments (0)