Type is safe to use for equality in Roslyn source generators
Lately I am playing a lot with Roslyn Source Code generators. This allows you to do interesting things, like automatic generation of validation classes based on data in the domain layer. Or generating tests that check if your API endpoints return 200 OK when a bare GET request is sent.
One thing you have to remember to do is use types with strict value equality. Otherwise it may work incorrectly or it may leak memory. You can, for example, use records that do that for you, with the gotcha being no extra fields or properties. Because of that I was mostly translating Types into other values, i.e., the full name of the type, to avoid equality issues. But it turns out you can use it in IValueProvider directly.
Type is safe for equality. You can safely define a Type as part of a record:
public sealed record JsonFileType(Type Type, string FileName, string Path);
It can also be part of a tuple:
var resultProvider = typeValueProvider.Combine(stringValueProvider); //results in (Type, string)
It will work because types (including generic types, even created with type.MakeGenericType()) all return the same RuntimeType within the same process, and since Equals and GetHashCode use this RuntimeType for equality, it is effectively reference equality between different type instances.
There are a few gotchas:
- if this is a type that is imported or loaded from another assembly - it can change
- dynamically created types (i.e., with
TypeBuilder) do not have a stableRuntimeType- so it also can change - such a cache does not work for short lived generator runs like
dotnet build(but then the cache does not matter at all) - if you do not need any extra information from the type (like methods information), it is better to use some other structure instead of
Type, i.e., thetype.FullNamestring
But if your generator relies on some signatures or information about members, using typeof(int) as a denominator, it is totally safe to cache it inside the Roslyn generator pipeline as the Int type won’t depend on Compilation.