What is the use of XML comments in C# - c#

What is the use of XML comments in C# than signal line and multiple line comments.
i.Single line
Eg:
//This is a Single line comment
ii. Multiple line (/* */)
Eg:
/*This is a multiple line comment
We are in line 2
Last line of comment*/
iii. XML Comments (///).
Eg:
/// summary;
/// Set error message for multilingual language.
/// summary

From XML Documentation Comments (C# Programming Guide):
When you compile with the /doc option, the compiler will search for
all XML tags in the source code and create an XML documentation file.
Also XML comments used by Visual Studio for IntelliSense:
/// <summary>
/// This class performs an important function.
/// </summary>
public class MyClass{}
Will give you nice hints when you are typing code or hovering cursor over member which has xml comments:
NOTE: Usually you should add xml comments only to publicly visible types or members. If member is internal or private, then it's good, but not necessary. There is nice tool GhostDoc (available as extension to Visual Studio) which can generate XML comments from type or member name. It's nice to check if you have good naming - if generated comment is not clear, then you should improve name of member.
I also suggest use simple (non-xml) comments as little, as possible. Because comment is a form of code duplication - it duplicates information which you already have in your code. And here is two problems:
Your code is not clear enough and you should improve it (renaming, extracting classes or members) instead of adding comments
When code changes, comments often stay unchanged (programmers are lazy). So when time passes comments become obsolete and confusing.
Good comments should describe why you writing code instead of duplicating what code is doing.

XML comments, starting with ///, will get picked up by IntelliSense and it will get shown in a pop-up when looking at it from elsewhere. There is a MSDN page explaining how it works.
They will also be picked up by numerous tools that build documentation files, etc.

From MSDN:
When you compile with the /doc option, the compiler will search for
all XML tags in the source code and create an XML documentation file.
To create the final documentation based on the compiler-generated
file, you can create a custom tool or use a tool such as Sandcastle.
http://msdn.microsoft.com/en-us/library/b2s063f7.aspx

The XML comments are used to build API documentation which is readable by external tools. IntelliSense also reads these, and uses the contents to show the docs for your code in the assistance tooltips as you type (and in the Documentation window).
The compiler (optionally) extracts all those comments and puts them in a single standalone XML file next to your assembly; this can be parsed.
The idea was to have something like JavaDoc. Unfortunately Microsoft has failed to provide a mainstream mature tool to do so.

When you create a Dll assambly Xml comments provides the dll's user some information about function or something

Code in all languages usually allows for special comments. These comments can then be parsed by a process which creates automatic documentation of the code. Many libraries are documented this way.
In C# these tools are provided by Microsoft and you use the XML comments to declare that the comment should be picked up by the documentation process - if you have one set up. The comments are also picked up by auto complete.
See also doxygen, JavaDoc for implementations for other languages. See related question Good alternatives to Sandcastle to generate MSDN-style documentation

Related

Does exist any C# documentation standards? [duplicate]

What is the use of XML comments in C# than signal line and multiple line comments.
i.Single line
Eg:
//This is a Single line comment
ii. Multiple line (/* */)
Eg:
/*This is a multiple line comment
We are in line 2
Last line of comment*/
iii. XML Comments (///).
Eg:
/// summary;
/// Set error message for multilingual language.
/// summary
From XML Documentation Comments (C# Programming Guide):
When you compile with the /doc option, the compiler will search for
all XML tags in the source code and create an XML documentation file.
Also XML comments used by Visual Studio for IntelliSense:
/// <summary>
/// This class performs an important function.
/// </summary>
public class MyClass{}
Will give you nice hints when you are typing code or hovering cursor over member which has xml comments:
NOTE: Usually you should add xml comments only to publicly visible types or members. If member is internal or private, then it's good, but not necessary. There is nice tool GhostDoc (available as extension to Visual Studio) which can generate XML comments from type or member name. It's nice to check if you have good naming - if generated comment is not clear, then you should improve name of member.
I also suggest use simple (non-xml) comments as little, as possible. Because comment is a form of code duplication - it duplicates information which you already have in your code. And here is two problems:
Your code is not clear enough and you should improve it (renaming, extracting classes or members) instead of adding comments
When code changes, comments often stay unchanged (programmers are lazy). So when time passes comments become obsolete and confusing.
Good comments should describe why you writing code instead of duplicating what code is doing.
XML comments, starting with ///, will get picked up by IntelliSense and it will get shown in a pop-up when looking at it from elsewhere. There is a MSDN page explaining how it works.
They will also be picked up by numerous tools that build documentation files, etc.
From MSDN:
When you compile with the /doc option, the compiler will search for
all XML tags in the source code and create an XML documentation file.
To create the final documentation based on the compiler-generated
file, you can create a custom tool or use a tool such as Sandcastle.
http://msdn.microsoft.com/en-us/library/b2s063f7.aspx
The XML comments are used to build API documentation which is readable by external tools. IntelliSense also reads these, and uses the contents to show the docs for your code in the assistance tooltips as you type (and in the Documentation window).
The compiler (optionally) extracts all those comments and puts them in a single standalone XML file next to your assembly; this can be parsed.
The idea was to have something like JavaDoc. Unfortunately Microsoft has failed to provide a mainstream mature tool to do so.
When you create a Dll assambly Xml comments provides the dll's user some information about function or something
Code in all languages usually allows for special comments. These comments can then be parsed by a process which creates automatic documentation of the code. Many libraries are documented this way.
In C# these tools are provided by Microsoft and you use the XML comments to declare that the comment should be picked up by the documentation process - if you have one set up. The comments are also picked up by auto complete.
See also doxygen, JavaDoc for implementations for other languages. See related question Good alternatives to Sandcastle to generate MSDN-style documentation

Alternative to XML Documentation Comments in C#

When asking around for the conventions of documentation comments in C# code, the answer always leads to using XML comments. Microsoft recommends this approach themselves aswell. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/recommended-tags-for-documentation-comments
/// <summary>
/// This is an XML comment.
/// </summary>
void Foo();
However, when inspecting Microsoft's code, such as ASP.NET Core, comments instead look like this.
//
// Summary:
// A builder for Microsoft.AspNetCore.Hosting.IWebHost.
public interface IWebHostBuilder
Does the included doc generation tool work with this convention, or is there a documentation generation tool that uses this convention instead of XML? Why does Microsoft use this convention in their code instead of the XML comments they recommend themselves?
Why does Microsoft use this convention in their code instead of the XML comments they recommend themselves?
C# documentation comments provide a precise syntax for encoding many types of content and references, such as to types, parameters, URLs, and other documentation files. It uses XML to accomplish this, and so inherits XML's verbosity. Remember that XML comments go way back to C# version 1, when it was a much more verbose language than it is today.
To avoid the readability problems with XML, Visual Studio displays the comments in a simplified, plain text format. You couldn't run this format back through a compiler. For example, if a comment has the term customerId, it may be ambiguous as to whether it refers to a method parameter or a class field. The ambiguity occurs infrequently enough to not be a problem for a human.
Ideally, there's be a single format that was well-defined for compiler input with good readability that avoids boilerplate. There is an issue open to modernize the comment syntax, but unfortunately, it hasn't gone anywhere in 3 years.

C# // vs /// comments

Lately I started using /// to comment my C# code rather than // or /* because it is just much simpler to use. Today I started wondering why there were different types and came across this SO question which states that /// comments are for generating the xml documentation.
I can't find any advice with regards to on type of comments vs another on Google and I take that to mean that it doesn't matter either way. I'm not getting any ill effects so far from using /// to comment, but I'd hate to get into a habit now just to unlearn it later. As far as I can tell, if there are no metatags in the comments it does not get recognised as being documentation (or am I completely wrong on that?)
Before I riddle my code with /// comments, is this type of commenting a big no-no? Could there be potential problems from commenting this way?
Could there be potential problems from commenting this way?
Yes. When you decide to generate your project documentation, then it will have all those commented lines as part of your XML documentation. When you compile the code using /Doc extension then it generates a document using your XML comments (///). If you have used that to comment out your code, then the document generate will consider the commented out code for your documentation.
Please see:
XML Documentation Comments (C# Programming Guide)
How to: Generate XML Documentation for a Project
There isn't any technical difference as far as code compilation goes. They're all ignored.
I believe the /// comment is more of a convention to signify that you are commenting a particular code block with XML Documentation Comments. IDEs like Visual Studio are geared to recognise the different comment type and will visually style accordingly.
Given that is general convention to use standard // or /* */ comments, there's also the potential to confuse (or, more likely, annoy) other developers who will read your code.
If you use delvelopment help tools like resharper for example mostly they offer you such a functionalities of commenting acode block either with // or with /* ... */, these commented code blocks can be toggeled using these tools, this wouldnt work for you once you have 3 slashes instead of 2.
The issue with the documentation symbols is another one, you will get comments generated in your documentation without having the control on what stayes a acomment in code and what gets into the documetnation since you have all over ///, but i guess this is an issue one can configure inthe documentation generation tool.

SandCastle: Generating links for C# class name

When I used doxygen for my C++ projects, I simply wrote:
/**
* I can refer to SomeClass or even SomeClass::someMethod() without special markup.
*/
Then doxygen generates links from "SomeClass" and "SomeClass::someMethod()" strings to appropriate documentation.
Now I work with C# and want to use SandCastle for generation documentation form C# code. I realized that links should be constructed with xml tag:
/// <see cref="SomeClass"/> and <see cref="SomeClass.someMethod()"/>
I think that it is very cumbersome and unreadable.
Is it any way to generate links for class and methods without special markup?
How do you generate documentation for C# projects?
Thank you.
Is it any way to generate links for class and methods without special
markup?
I don't think so. Actually the XML documentation (format) is not a feature of sandcastle, but of the C# compiler. Sandcastle (and other tools, like NDoc) "simply" build on it.
How do you generate documentation for C# projects?
We're using Sandcastle and the Sandcastle Helpfile Builder (SHFB).
Also we're using GhostDoc and ReSharper which help with writing and (on-the-fly) validating XML comments, for example if the type, method, or else you reference actually exist.
I think you could also use Doxygen and thus Doxygen style comments with your C# code, but personally I have never tried it. You'd have to check the Doxygen website. But you would miss out on features other tools provide based on the XML documentation (like ReSharper's quick documentation) or most prominently, help-/description texts for Intellisense.

What Are Best Practices For Documenting C# code with XML comments?

I'm going through some new code I just wrote and adding NDoc sytle comments to my classes and methods. I'm hoping to generate a pretty good MSDN style document for reference.
In general, what are some good guidelines when writing comments for a class and for a method? What should the NDoc comments say? What should they not say?
I find myself looking at what the .NET framework comments say, but that gets old fast; if I could have some good rules to guide myself, I could finish my docs a lot faster.
In comments used to build API documentation, you should:
Explain what the method or property does, why it exists at all, and explain any domain concepts that are not self-evident to the average consumer of your code.
List all preconditions for your parameters (cannot be null, must be within a certain range, etc.)
List any postconditions that could influence how callers deal with return values.
List any exceptions the method may throw (and under what circumstances).
If similar methods exist, explain the differences between them.
Call attention to anything unexpected (such as modifying global state).
Enumerate any side-effects, if there are any.
If you end up with comments that don't add any value, they're just wasteful.
For example
/// <summary>
/// Gets manager approval for an action
/// </summary>
/// <param name="action">An action object to get approval for</param>
public void GetManagerApprovalFor(Action action)
...you added absolutely no value and just added more code to maintain.
Too often code is littered with these superfluous comments.
StyleCop provides hints for code and commenting style. The suggestions it gives are in line with the MSDN documentation style.
As for the contents of the comment, it should give the user of your code enough information on what kind of behavior to expect. It should also answer potential questions the user might have. So try to use your code as someone who doesn't know anything about the code, or even better, ask someone else to do so.
For properties, your comment should indicate whether the property is read only, write only or read write. If you look at all official MS documentation, property doc comments always start with "Gets ...", "Gets or sets..." and (very rarely, avoid write only properties usually) "Sets ..."
Don't forget what's a valid XML is. For example:
/// <Summary>
/// Triggers an event if number of users > 1000
/// </Summary>
(Error: invalid XML).
I write the <summary> comment to include the information I would want to know if I was the one calling that function (or instantiating that class).
I write the <remarks> comment to include information I would want to know if I was tasked with debugging or enhancing that function or class. Note: this doesn't replace the need for good inline comments. But sometimes a general overview of the inner workings of the function/class are very helpful.
As stated on the MSDN page, you use XML documentation comments to generate documentation automatically, so it makers sense if you're writing an API and don't want to work twice at both code and documentation, with the added benefit of keeping them in sync - every time you change the code, you modify the appropriate comments and regenerate the docs.
Compile with /doc and the compiler will search for all XML tags in the source code and create an XML documentation file, then use a tool such as Sandcastle to generate the full docs.
One thing about comments is UPDATING them. Too many people alter a function then don't change the comment to reflect the change.

Categories