title: C# string interpolation within a static context
body: <p>I'm currently trying to generate a class as <b>string</b> with some properties, which I've to set before compiling the code.</p>
  
  <p>Let's take a look at my code, I'm using a static string :</p>
  
  <pre><code>    public class NewHumanSource
      {
              static readonly string template =
                  "internal class {ClassName} : IHuman " + 
                  "{ " +
                       // bunch of private fields here;
                       "private int age; " + Environment.NewLine +
  
                       "public int Age" + Environment.NewLine +
                       "{" + Environment.NewLine +
                            "get =&gt;" + $"{int.Parse("{Age}")}" + ";" + Environment.NewLine +
                            "set" + Environment.NewLine +
                            "{" + Environment.NewLine +
                                 "age= value;" + Environment.NewLine +
                                 "OnPropertyChanged(nameof(age));" +Environment.NewLine +      
                            "}" + Environment.NewLine +
                       "}" + Environment.NewLine + Environment.NewLine +
  
                        // Other properties and members
                  ";"
  </code></pre>
  
  <p>The static member that is used to set values to the source code template :</p>
  
  <pre><code> public static string GetSourceCode(IHuman newHuman, string className)
   {
       code = code.Replace("{ClassName}", className.ToLowerInvariant().Replace(" ", ""));
       code = code.Replace("{Age}", newHuman.Age.ToString()); //Age is an integer.
       //...
   }
  </code></pre>
  
  <p>Then called from an external class : </p>
  
  <pre><code> var code = NewHumanSource.GetSourceCode(newHuman, className);
  </code></pre>
  
  <p>Exception is thrown at that line. The static method won't even load :</p>
  
  <pre><code>System.TypeInitializationException: 'The type initializer for 'DynamicCompilerTest.Classes.DynamicCompiler.NewHumanSource' threw an exception.'
  
  InnerException  {"Input string was not in a correct format."}   System.Exception {System.FormatException}
  </code></pre>
  
  <p>It'd would work just fine is all properties were strings but this string interpolation raises the exception : </p>
  
  <pre><code> "get =&gt;" + $"{int.Parse("{Age}")}" + ";" +
  </code></pre>
  
  <p>Any idea of how I should handle non string type ? I Need to handle built-in type like DateTime and such. Or is there even a more elegant way to create a class as text with properties values ? I might get ride of the formatting.</p>
  
  <p>Thanks a lot for your help / tips !</p>