C# // vs /// comments - c#

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.

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.

What is the use of XML comments in 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

Are there any tools which can report on commented-out .NET code?

Has anyone come across a tool to report on commented-out code in a .NET app? I'm talking about patterns like:
//var foo = "This is dead";
And
/*
var foo = "This is dead";
*/
This won't be found by tools like ReSharper or FxCop which look for unreferenced code. There are obvious implications around distinguishing commented code from commented text but it doesn't seem like too great a task.
Is there any existing tool out there which can pick this up? Even if it was just reporting of occurrences by file rather than full IDE integration.
Edit 1: I've also logged this as a StyleCop feature request. Seems like a good fit for the tool.
Edit 2: Yes, there's a good reason why I'd like to do this and it relates to code quality. See my comment below.
You can get an approximate answer by using a regexp that recognizes comments, that end with ";" or "}".
For a more precise scheme, see this answer:
Tool to find commented out VHDL code
I've been done this road for the same reason. I more or less did was Ira Baxter suggested (though I focused on variable_type variable = value and specifically looked for lines that consisted of 0 or more whitespace at beginning followed by // followed by code (and to handle /* */, I wrote a preprocessor that converted it into //'s. I tweaked the reg exp to cut down on false positives and also did a manual inspection just to be safe; fortunately, there were very few cases where the comment was doing pseudo-code like things as drachenstern suggests above; YMMV. I'd love to find a tool that could do this but some false positives from valid but possibly overly detailed pseudo code are going to be really to rule out, especially if they're using literate programming techniques to make the code as "readable" as pseudo code.
(I also did this for VB6 code; on the one hand, the lack of ;'s made it harder to right an "easy" reg exp, on the other hand the code used a lot less classes so it was easier to match on variable types which tend not to be in pseudo code)
Another option I looked at but didn't have available was to look at the revision control logs for lines that were code in version X and then //same line in version Y... this of courses assumes that A) they are using revision control B) you can view it, and C) they didn't write code and comment it out in the same revision. (And gets a little trickier if they use /* */ comments
There is another option for this, Sonar. It is actually a Java centric app but there is a plugin that can handle C# code. Currently it can report on:
StyleCop errors
FxCop errors
Gendarme errors
Duplicated code
Commented code
Unit test results
Code coverage (using NCover, OpenCover)
It does take a while for it to scan mostly due to the duplication checks (AFAIK uses text matching rather than C# syntax trees) and if you use the internal default derby database it can fail on large code bases. However it is very useful to for the code-base metrics you gain and it has snapshot features that enable you to see how things have changed and (hopefully) got better over time.
Since StyleCop is not actively maintained (see https://github.com/StyleCop/StyleCop#considerations), I decided to roll out my own, dead-csharp:
https://github.com/mristin/dead-csharp
Dead-csharp uses heuristics to find code patterns in the comments. The comments starting with /// are intentionally ignored (so that you can write code in structured comments).
StyleCop will catch the first pattern. It suggests you use //// as a comment for code so that it will ignore the rule.
Seeing as you mentioned NDepends it also can tell you Percentage commented http://www.ndepend.com/Metrics.aspx#PercentageComment. This is defined for application, assemblies, namespaces, types and methods.

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