C
C#6h ago
Ruttie

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
Buddy
Buddy6h ago
You can use a source generator / analyzer
Ruttie
RuttieOP6h ago
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
ACiDCA7
ACiDCA76h ago
im curious, whats the usecase?
Ruttie
RuttieOP5h ago
creating monomod hooks using attributes (source generation) while ensuring the hooked and the replacing methods are compatible
Aaron
Aaron5h ago
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
Ruttie
RuttieOP5h ago
what about a source generator? does it have the same access as analyzers?
Aaron
Aaron5h ago
yes how are you referencing types in your attribute Type or string
Ruttie
RuttieOP5h ago
given I need methods, I plan on using type and string for method name
Aaron
Aaron5h ago
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
Ruttie
RuttieOP5h ago
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
Aaron
Aaron5h ago
yes that is possible even without putting them in one assembly by just having them in the same package

Did you find this page helpful?