Home > Software engineering >  Is there a way to modify C# code with C#?
Is there a way to modify C# code with C#?

Time:01-27

How can I add a statement public int ID { get; set; } to the class below programmatically?

public class DgItem
{
    public string Name { get; set; }
}

CodePudding user response:

Use T4 Templates!

https://docs.microsoft.com/en-us/visualstudio/modeling/code-generation-and-t4-text-templates?view=vs-2022

<#@ output extension=".cs" #>
public class DgItem
{
<# for (int i = 0; i < 10; i  )
    {
#>
    public string Name<#= i #> { get; set; }
<# }
#>
}

output:

public class DgItem
{
    public string Name0 { get; set; }
    public string Name1 { get; set; }
    public string Name2 { get; set; }
    public string Name3 { get; set; }
    public string Name4 { get; set; }
    public string Name5 { get; set; }
    public string Name6 { get; set; }
    public string Name7 { get; set; }
    public string Name8 { get; set; }
    public string Name9 { get; set; }
}
  •  Tags:  
  • Related