Post

record, FrozenDictionary, WireMock

record, FrozenDictionary, WireMock

Everything You Want to Know About the Record Type in .NET… But Were Afraid to Ask

I should remember to use C# record types more often.

  • use init for properties to make them immutable (only settable in the constructor)
  • clone record by using with
  • equality and comparison methods are automatically generated
  • hashing and ToString methods are automatically generated

C# Records

Continuing the same subject, this article reminds us that there are two ways of defining constructors:

1
public record Song(string artist, string title);

is the same as

1
2
3
4
5
public record Song
{
    public string Title { get; init; }
    public string Artist { get; init; }
}

but it’s also possible to use set instead of init in the above, which makes the properties mutable (I’m not sure why you’d want that).

Also, about with:
This is copying the reference, not cloning:

1
song2 = song1;

This is a creating a clone:

1
song2 = song1 with {};

This is a copy with a different value for one property:

1
song2 = song1 with { Title = "It's me" };

FrozenDictionary under the hood: how fast is it comparing to Dictionary and why

In case you ever need an immutable dictionary, .Net 8 introduced FrozenDictionary. Apart from the obvious case of making it explicit that it’s immutable, the fact that’s it’s immutable allows for some performance improvements such that it’s always faster than a regular Dictionary.

How to use IHttpClientFactory and WireMock.NET together using Moq

Nice explanation of how to use WireMock to test classes that use IHttpClientFactory.

Your class has IHttpClientFactory injected into it and calls CreateClient() on it to get an HttpClient.

To test this class:

  • Create a WireMock server called _server in OneTimeSetUp
  • Configure your mocked IHttpClientFactory.CreateClient() to return _server.CreateClient()
  • Setup your tests to do things like this:
1
2
3
_server
  .Given(Request.Create().WithPath("/api/books/42").UsingGet())
  .RespondWith(Response.Create().WithStatusCode(404));
This post is licensed under CC BY 4.0 by the author.