A typesafe way of adding with-functionality to any type.
$ dotnet add package Typesafe.WithProviding with-functionality to any type on the .NET platform.
Typesafe.With is a strongly typed way to change properties on immutable types that lets you:
Typesafe.With supports types using:
PM> Install-Package Typesafe.With
Typesafe.With allows you to update properties on immutable types in a type safe way that is type checked by the compiler.
Typesafe.With provides a single method called With.
Any call to With produces a new instance of the immutable type with the updated property.
The call to With is strongly typed which means that the compiler verifies that the assignment is valid.
To use Typesafe.With simply import the following namespace:
using Typesafe.With;
public class Person
{
public string Name { get; }
public Person(string name) => (Name) = (name);
}
var harry = new Person("Harry Potter");
var hermione = harry.With(p => p.Name, "Hermione Granger");
Console.WriteLine(hermione.Name); // Prints "Hermione Granger"
public enum House { Gryffindor, Slytherin }
public class Person
{
public string Name { get; }
public House House { get; }
public Person(string name, House house) => (Name, House) = (name, house);
}
var harry = new Person("Harry Potter", House.Gryffindor);
var malfoy = harry
.With(p => p.Name, "Malfoy")
.With(p => p.House, House.Slytherin);
Console.WriteLine(malfoy.Name); // Prints "Malfoy"
Console.WriteLine(malfoy.House); // Prints "Slytherin"
public enum House { Gryffindor, Slytherin }
public class Person
{
public string Name { get; }
public House House { get; }
public Person(string name, House house) => (Name, House) = (name, house);
}
var harry = new Person("Harry Potter", House.Gryffindor);
var malfoy = harry
.With(p => p.House, house => house == House.Slytherin ? House.Gryffindor : house);
Console.WriteLine(malfoy.House); // Prints "Gryffindor"The resulting type T is constructed via the following steps:
T<sup>+</sup> The constructor taking the most arguments. If there is no constructor, the default constructor is called.
In step 2, if the constructor C takes the argument to be swapped, the
Typesafe.With relies on the convention that the property is named the same in the type constructor.