invio / Invio.Immutable

C# Library used to ease immutable class creation and data management
MIT License
2 stars 0 forks source link

Add [StringComparison]-like annotation for String properties #12

Closed carusology closed 6 years ago

carusology commented 7 years ago

It is common for strings to be compared by ignoring case or performing ordinal comparisons versus culture-specific ones. However, you cannot do this type of comparison with ImmutableBase<TImmutable>. You're currently stuck with the default string comparison ordinal and case-sensitive. While I think complex comparisons, such as those where two properties need to be compared to determine equality, should be implemented by the developer, this is a common enough comparison that it warrants first-class support.

It would be done via something like this:

public class MyImmutable : ImmutableBase<MyImmutable> {

    public String UseDefaultComparison { get; }

    [StringComparisonAttribute(StringComparison.OrdinalIgnoreCase)]
    public String UseOrdinalIgnoreCaseComparison { get; }

    public MyImmutable(
        String useDefaultComparison,
        String useOrdinalIgnoreCaseComparison) {

        this.UseDefaultComparison = useDefaultComparison;
        this.UseOrdinalIgnoreCaseComparison = useOrdinalIgnoreCaseComparison;
    }

}

Give the above example, I would expect values in the UseOrdinalIgnoreCaseComparison property to be compared without regard to case, and values in the UseDefaultComparison property to be compared with regard to case. Here are some tests that codify these assumptions:

public class MyImmutableTests {

    [Fact]
    public void IgnoreCase() {
        var left = new MyImmutable("foo", "bar");
        var right = new MyImmutable("foo", "BAR");

        Assert.Equal(left, right);
    }

    [Fact]
    public void CaseSensitiveByDefault() {
        var left = new MyImmutable("foo", "bar");
        var right = new MyImmutable("FOO", "bar");

        Assert.NotEqual(left, right);
    }

}