Skip to content

A Fody addin to extend immutable C# classes with With() methods to return a copy of an object with one property modified.

License

Notifications You must be signed in to change notification settings

mikhailshilkov/With.Fody

Folders and files

NameName
Last commit message
Last commit date

Latest commit

author
mikhailshilkov
Mar 8, 2017
94ae5c5 · Mar 8, 2017

History

20 Commits
Mar 8, 2017
May 3, 2016
May 7, 2016
Mar 8, 2017
Mar 8, 2017
Mar 8, 2017
May 3, 2016
May 3, 2016
May 15, 2016
Mar 8, 2017
May 3, 2016

Repository files navigation

This is an add-in for Fody

Icon

A Fody addin to extend immutable C# classes with With() methods to return a copy of an object with one field modified.

Introduction to Fody.

The nuget package NuGet Status

https://nuget.org/packages/With.Fody/

PM> Install-Package With.Fody

Your Code

public class MyClass
{
    public MyClass(int intValue, string stringValue, OtherClass c1, OtherClass c2)
    {
        this.IntValue = intValue;
        this.StringValue = stringValue;
        this.C1 = c1;
        this.C2 = c2;
    }

    public int IntValue { get; }

    public string StringValue { get; }

    public OtherClass C1 { get; }

    public OtherClass C2 { get; }

    // Needed for IntelliSense/Resharper support
    public MyClass With<T>(T value) => this;
    // If two properties have same type, we need to append the property name to With
    public MyClass WithC1(OtherClass value) => this;
    public MyClass WithC2(OtherClass value) => this;
}

What gets compiled

public class MyClass
{
    public MyClass(int intValue, string stringValue, OtherClass c1, OtherClass c2)
    {
        this.IntValue = intValue;
        this.StringValue = stringValue;
        this.C1 = c1;
        this.C2 = c2;
    }

    public int IntValue { get; }

    public string StringValue { get; }

    public OtherClass C1 { get; }

    public OtherClass C2 { get; }

    public MyClass With(int value)
    {
        return new MyClass(value, this.StringValue, this.C1, this.C2);
    }

    public MyClass With(string value)
    {
        return new MyClass(this.IntValue, value, this.C1, this.C2);
    }

    // If two properties have same type, we need to append the property name to With
    public MyClass WithC1(OtherClass value)
    {
        return new MyClass(this.IntValue, this.StringValue, value, this.C2);
    }

    public MyClass WithC2(OtherClass value)
    {
        return new MyClass(this.IntValue, this.StringValue, this.C1, value);
    }
}

Motivation

The motivation behind this plugin is explained in the post Tweaking immutable objects with C# and Fody.

Icon

Icon created by Yazmin Alanis from Noun Project

About

A Fody addin to extend immutable C# classes with With() methods to return a copy of an object with one property modified.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages