Search code examples
c#buildprecompile

Possible to pass a constant to C# compiler in build script


I have a C# file with something like this:

public const string QueueName = "abc";

and I would like to build the application several times switching this value each time. It is NOT possible to change QueueName to anything other than a compile-time constant.

Is there any way to pass a 'pre-compiler' variable to this declaration that could be changed in a build configuration or build script?

I have googled it but I can't seem to get any solution.


Solution

  • Since these are constants, you could consider using code generation with a T4 template to generate the constants and the values on build in a separate class file.

    The proper constantvalues from this class file can come from an array, database or other external source.

    Code would be something like:

       <#@ output extension=".cs" #>
        <#
           using(SampleContext context = new SampleContext)
           {
           string queuename = context.Queuename.FirstOrDefault();
           }
        #>
        internal class NotSoConstantConstants
        {
           public const string QueueName = "<#= queuename #>";
        }
    

    which can output to:

    internal class NotSoConstantConstants
    {
      public const string QueueName = "abc";
    }