InternetException

C#

C# · 2 posts (all tags)

C# Record's auto equality comparison

· 1028 words · ~5 min read · in .NET

#C# #records #gotchas

I always thought that when you write a record:

public record MyRecord(int Id, string Name)
{
    public string Description { get; set; }
}

The Description property won’t matter for equality because it is mutable. I always thought about records as immutable structures: once declared and put in a collection, their value will not change - and so their equality will not change just because you set a property. So it was very surprising, and it kind of defeats the whole purpose of a record.

Why is it like that?

Read the whole thing →

Pattern matching

· 103 words · ~1 min read · in .NET, interview

#design patterns #SOLID #C#

Pattern matching is used for: testing expression to check if some value have certain characteristics safer compare because ‘==’ and ‘!=’ can be overloaded Examples: a is int number sequence is IList<T> list switch statement: command switch { Operation.SystemTest => RunDiagnostics(), Operation.Start => StartSystem(), Operation.Stop => StopSystem(), Operation.Reset => ResetToReady(), _ => throw new ArgumentException("Invalid enum value for command", nameof(command)), }; switch with ranges: tempInFahrenheit switch { (> 32) and (< 212) => "liquid", < 32 => "solid", > 212 => "gas", 32 => …

Read the whole thing →