Immutable record types for c#
Install following nuget packages into your project:
- Records
- CodeGeneration.Roslyn.Tool
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;
}
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);
}
Good news!
It seems Records will appear in C# 9