How do I escape characters in c# comments?
If you need to escape characters in XML comments, you need to use the character entities, so <
would need to be escaped as <
, as in your question.
The alternative to escaping is using CDATA
sections, to the same effect.
As you noted, this would produce good looking documentation, but a horrible comment to read...
In plain C# comments you can use any character (except */
if you started the comment with /*
, or the newline character if you started the comment with //
). If you are using XML comments then you can use a CDATA section to include '<' and '>' characters.
See this MSDN blog article for more information on XML comments in C#.
For example
/// <summary>
/// Here is how to use the class: <![CDATA[ <test>Data</test> ]]>
/// </summary>
You said "I want to make it easy to read the comment in the actual document". I agree.
Developers spend most of their lives in the code, not perusing auto-generated docs. Those are great for thirdparty libraries like charting, but not for in-house development where we work with all of the code. I'm sort of shocked that MSFT hasn't come up with a solution that supports developers better here. We have regions that dynamically expand/collapse code...why can't we have an in-place comment rendering toggle (between raw text and processed XML comment or between raw text and processed HTML comment)?. Seems like I should have some elementary HTML capabilities in my method/class prologue comments (red text, italics, etc). Surely an IDE could work a little HTML processing magic to liven up inline comments.
My hack-of-a-solution solution: I change '<' to "{" and '>" to "}". That seems to cover me for the typical example usage style comment, including your specific example. Imperfect, but pragmatic given the readability issue (and problems with IDE comment coloring that ensue when using '<')