Add CodeCommentStatement to CodeMemberProperty When Generate C# code with CodeDOM

StackOverflow https://stackoverflow.com/questions/23294464

  •  09-07-2023
  •  | 
  •  

Question

Does anyone know how to Add CodeCommentStatement to CodeMemberProperty When Generate C# code with CodeDOM ?

I tried:

var docStart = new CodeCommentStatement("<summary>", true);
var docContent = new CodeCommentStatement("The description of property", true);
var docEnd = new CodeCommentStatement("</summary>", true);

var property = new CodeMemberProperty {
    Name = name,
    HasGet = true,
    Attributes = MemberAttributes.Public | MemberAttributes.Static,
    Type = new CodeTypeReference(typeof(byte[]))    
};

var documentation = new CodeCommentStatementCollection { docStart, docContent, docEnd}
property.Comments = new CodeCommentStatementCollection(documentation);

But Comments property hasn't setter...

enter image description here

Is there a workaround?

Was it helpful?

Solution

I'd propose to add the items to the existing CodeCommentStatementCollection instead of creating a new one:

CodeCommentStatement[] documentation = { docStart, docContent, docEnd}
property.Comments.AddRange(documentation);

The collection provides the common methods for adding: Add, AddRange for an array, AddRange for a CodeCommentStatementCollection.

As pointed out by @svick in the comments, you can also assign the value when instantiating the object, e.g.

var property = new CodeMemberProperty {
                   // Other initialization values
                   Comments = { docStart, docContent, docEnd } }

In case you wonder why and how this works on a readonly property, see this question and its answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top