is there a way Generate C# automatic properties with Codedom or maybe an other set of libreries that i can use ?
5 Answers
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);
Comments
No, it's not: C# CodeDom Automatic Property
Take a look into this article to get some useful examples
5 Comments
Hannoun Yassir
so are there any other libraries that i can use ?
chakrit
@Yassir It's really not that hard to create a backing field and use them in getter/setter.
Rubens Farias
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)
Hannoun Yassir
actually i'm not compiling the generated code i add it to a project so i need the generated classes to have automatic properties
Rubens Farias
In that case, you could to use a
CodeSnippetStatement and hardcode that propertyCodeDom 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
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
Mohsen Afshin
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