How to add a property to an existing class programmatically?

584 Views Asked by At

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; } 
}
1

There are 1 best solutions below

1
philippe On BEST ANSWER

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