classpropertiest4partialcodedom

How to add a property to an existing class programmatically?


I want to add another property public int ID { get; set; } to the class below using C#. I don't know if there is a way beside T4 or partial class. How about CodeDom? I'm not familiar with it. Please do me a favor, Thanks!

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

Solution

  • You create a field for your property

    CodeMemberField cmf = new CodeMemberField(new CodeTypeReference(type), name);
    cmf.Attributes = attr;
    cmf.InitExpression = new CodePrimitiveExpression(value);
    

    You create your property

    CodeMemberProperty cmp = new CodeMemberProperty()
       {
       Name = name,
       Type = new CodeTypeReference(type),
       Attributes = attr,
       };
    

    Then add the get and set statements

    cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), field.Name)));
    cmp.SetStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), field.Name), new CodePropertySetValueReferenceExpression()));
    

    And that should do the trick