Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to arrange for code to run at compile time in C#

Tags:

c#

Is there a possibility to execute some code during compile time?

For example, I would like to check if the requested methods of a dynamic object exist in the parameter-type of a generic class.

 // This code has no actual purpose, just as an example
 public class Sample<T>
 {
     public Sample<T>(T instance)
     {
         foo = Value = instance;
         /* adding some extra code(e.g. logging) to the methods of T, by
inserting a "M" in front of the method names of T */
     }

     public T Value { get; }
     public dynamic foo { get; }
 }

How it would/could be used

var foo = new Sample<string>("hey");
foo.MSubstring(0,0);

Now I want to know if there's a possibility to execute code at compile time, e.g., to throw an exception before runtime that foo.MgetSize() doesn't exist in T.

(This question is only about how to execute code at compile time, and this sample isn't a real problem.)

I don't have a plan how to do that. Maybe using those #if- things?

like image 901
leAthlon Avatar asked Oct 27 '25 06:10

leAthlon


1 Answers

Yes, it is possible to execute code at build time. After all, the tools that build your program are, themselves, code.

What you're asking is how to customize that build process and execute some additional logic during it. How you would do this depends on the actual tools you're using - for example, for Visual Studio and the MSBuild system, you can refer to the MSDN documentation on custom build steps and build events.

What your custom build tool would be like depends on what part of the process it will fire up in. If it works with source code, it needs to be able to parse C# source code (and probably Visual Studio project files as well). If it works by verifying the emitted assembly (the binary that's produced at the end of the typical build process), it could simply use reflection to detect the errors you want. I'd say the latter is more convenient.

like image 157
Theodoros Chatzigiannakis Avatar answered Oct 29 '25 20:10

Theodoros Chatzigiannakis