Skip to content

sobolev88/Records

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Records

GitHub Actions CI status NuGet package

Immutable record types for c#

Installation

Install following nuget packages into your project:

  1. Records
  2. CodeGeneration.Roslyn.Tool

Features

Constructor generating

If we declare class User like this:

    [Record]
    public partial class User
    {
        public Guid Id { get; } = Guid.NewGuid();

        public DateTimeOffset CreatedAt { get; } = DateTimeOffset.UtcNow;

        public string FirstName { get; }

        public string LastName { get; }

        public string? MiddleName { get; }

        public DateTime? BirthDate { get; }
    }

the following constructor would be generated:

        public User(string firstName,
                    string lastName,
                    Guid? id = default(Guid?),
                    DateTimeOffset? createdAt = default(DateTimeOffset?),
                    string? middleName = default(string?),
                    DateTime? birthDate = default(DateTime?))
        {
            FirstName = firstName;
            LastName = lastName;
            if (id != null)
                Id = id.Value;
            if (createdAt != null)
                CreatedAt = createdAt.Value;
            MiddleName = middleName;
            BirthDate = birthDate;
        }

With methods generating

If we specify with parameter in Record attribute like this:

    [Record(with: true)]
    public partial class User
    {
        public Guid Id { get; } = Guid.NewGuid();

        public string FirstName { get; }

        public string LastName { get; }

        public string? MiddleName { get; }
    }

the following methods and constructor would be generated:

        public User(string firstName,
                    string lastName,
                    Guid? id = default(Guid?),
                    string? middleName = default(string?))
        {
            FirstName = firstName;
            LastName = lastName;
            if (id != null)
                Id = id.Value;
            MiddleName = middleName;
        }

        public User WithFirstName(string firstName)
        {
            return new User(firstName, LastName, Id, MiddleName);
        }

        public User WithLastName(string lastName)
        {
            return new User(FirstName, lastName, Id, MiddleName);
        }

        public User WithId(Guid id)
        {
            return new User(FirstName, LastName, id, MiddleName);
        }

        public User WithMiddleName(string? middleName)
        {
            return new User(FirstName, LastName, Id, middleName);
        }

C# 9

Good news!
It seems Records will appear in C# 9