Is it appropriate to use C# records for encapsulating objects other than data?

Viewed 442

Records are great for encapsulating data, but what about things like services and repositories? The positional syntax for property definition is more concise compared to class definition code, since the constructor, properties, and property initialization code are generated by the compiler for us.

Here is a contrived example to demonstrate. The intent is to make the dependencies of RecordService immutable in fewer lines of code. In a real-world scenario, the dependencies would be injected by a service container.

namespace RecordsTest;

class MyRepo
{
    public string SomeMethod() => "MyRepo.SomeMethod()";
}

class MyService
{    
    public string SomeMethod() => "MyService.SomeMethod()";
}

record RecordService(MyRepo Repo, MyService Service)
{
    public void SomeMethod() => 
        Console.WriteLine($"RecordService.SomeMethod() {Repo.SomeMethod()} {Service.SomeMethod()}");
}

class Program
{
    static void Main(string[] args)
    {
        var myRepo = new MyRepo();
        var myService = new MyService();

        var recordService = new RecordService(myRepo, myService);
        recordService.SomeMethod();

        Console.ReadKey();
    }
}
1 Answers

Records provide the following functionality (source)

  • Concise syntax for creating a reference type with immutable properties
  • Built-in behavior useful for a data-centric reference type:
    • Value equality
    • Concise syntax for nondestructive mutation
    • Built-in formatting for display
  • Support for inheritance hierarchies

Your example only really benefits from the construction syntax, but that makes the declared properties public. That is typically not something you want when writing a service. And if you specify the properties explicitly you gain almost nothing from using records.

So I would in general recommend using records when you want to describe data, and regular classes for services or other code that focus on functionality rather than data. But I expect there to be some overlap where either might be appropriate.

Related