Check that two function signatures are equal at compile-time
I have two C# methods, which we'll call method A and B.
I know the exact signature of A, but not of B.
I want to write some C# code that, at compile time, ensures that A and B have the same signature.
However, the equality should be somewhat loose, for example if B is an instance method with no parameters and no return value, and A is a method with as sole parameter the class B resides in and no return value, they should be equal.
Is this possible?
11 Replies
You can use a source generator / analyzer
This is actually related to a source generator, however method B would be in a different (referenced) assembly, hence I can't access the signature of B
is it possible to get types from referenced dlls?
I realize this post may be suffering from the XY problem
im curious, whats the usecase?
creating monomod hooks using attributes (source generation) while ensuring the hooked and the replacing methods are compatible
in an analyzer yes, this isn't very hard
with the caveat that Roslyn doesn't really load anything private into it's models
so you can't check the signatures of private methods
what about a source generator?
does it have the same access as analyzers?
yes
how are you referencing types in your attribute
Type or string
given I need methods, I plan on using type and string for method name
then it would be fairly easy even from within a source generator, though correctly emitting diagnostics from source generators is much more annoying
https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.cookbook.md#issue-diagnostics
is it possible to put an analyzer and generator in one assembly?
if so, maybe it'd be possible to force the user to use the analyzer alongside the generator
yes
that is possible even without putting them in one assembly by just having them in the same package