9

is there a way Generate C# automatic properties with Codedom or maybe an other set of libreries that i can use ?

5 Answers 5

8

You can use CodeSnippetTypeMember class for that purpose.

For example:

    CodeTypeDeclaration newType = new CodeTypeDeclaration("TestType");
    CodeSnippetTypeMember snippet = new CodeSnippetTypeMember();
    snippet.Comments.Add(new CodeCommentStatement("this is integer property", true));
    snippet.Text="public int IntergerProperty { get; set; }";
    newType.Members.Add(snippet);
Sign up to request clarification or add additional context in comments.

Comments

6

No, it's not: C# CodeDom Automatic Property

Take a look into this article to get some useful examples

5 Comments

so are there any other libraries that i can use ?
@Yassir It's really not that hard to create a backing field and use them in getter/setter.
you dont need; as Marc Gravell said, you need to implement it yourself, as they are just a compiler trick (i.e. .net compiler creates a private variable to hold your automatic property value)
actually i'm not compiling the generated code i add it to a project so i need the generated classes to have automatic properties
In that case, you could to use a CodeSnippetStatement and hardcode that property
2

CodeDom is supposed to be some sort of AST which can be converted to multiple languages (typically C# and VB.NET). Therefore, you'll not find features which are syntactic sugar of a specific language in CodeDom.

Comments

1

Actually the comments about it being easy to use a CodeSnippetStatement are misleading because CodeTypeDeclaration has no statements collection that you can add those snippets to.

Comments

-2

You can do this: According to How to: Create a Class Using CodeDOM

        // Declare the ID Property.
        CodeMemberProperty IDProperty = new CodeMemberProperty();
        IDProperty.Attributes = MemberAttributes.Public;
        IDProperty.Name = "Id";
        IDProperty.HasGet = true;
        IDProperty.HasSet = true;
        IDProperty.Type = new CodeTypeReference(typeof(System.Int16));
        IDProperty.Comments.Add(new CodeCommentStatement(
        "Id is identity"));
        targetClass.Members.Add(IDProperty);

1 Comment

This does not work, as it generates two empty set and get methods which will result in compiling errors. The CodeSnippetTypeMember (stackoverflow.com/a/23876973/191148) is the solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.