andrewlock / StronglyTypedId

A Rosyln-powered generator for strongly-typed IDs
MIT License
1.52k stars 80 forks source link

GetHashCode fails in certain cases when Backing Type is String #49

Open Miljankg opened 2 years ago

Miljankg commented 2 years ago

Hi!

Thanks for creating this library, I really like it. As I was using it within my project I had several ids with a backing type of String. On certain occasions, these ids were created using a default, parameterless constructor. When GetHashCode was invoked on those ids the NullReferenceException was thrown, and that what a bit against what I would expect.

I have attached a .CS file containing tests you can run to reproduce the issue (I had some issues with dotnetfiddle).

Tests.txt

Some of my thoughts on this:

In the end, if you opt for addressing this, I would be happy to implement the solution and contribute to your project :)

SteveDunn commented 2 years ago

It's incredibly difficult to fully find and warn of instances where value types contain uninitialised reference types.

I have a similar library to Andrew's, but they concentrate on different things. Mine (Vogen) concentrates on validity of 'Value Objects' (domain concepts). It has analyzers that help you stop creating invalid instances: https://twitter.com/SteveDunn/status/1495894535850844167

I wrote about the issues here: https://dunnhq.com/posts/2022/non-defaultable-value-types/

Miljankg commented 2 years ago

@SteveDunn thanks for the reply and the article. Actually, I was talking about the same thing (analyzers) you have implemented in your library.

As for the GetHashCode throwing NullReferenceException, I think that can be easily avoided in the GetHashCode implementation.

SteveDunn commented 2 years ago

I hope that the analyzers and runtime checks wouldn't even get as far as GetHashCode