C# Comments

Comments can be used to explain C# code, and to make it more readable. It can also be used to prevent execution when testing alternative code.

 

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by C# (will not be executed).

This example uses a single-line comment before a line of code:


// namespaces
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
...

 

C# Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by C#.

This example uses a multi-line comment (a comment block) to explain the code:


/* namespaces
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;*/
...

 

C# Comments Best Practices

 

Namespace Comment:

Namespace comments help developer to understand the complete detail and purpose of the class. 


/// <summary>
///   Namespace        :      Core
///   Class            :      UserServices
///   Description      :      User related services goes here
///   Author           :      GrayDart                   Date: Aug 08, 2021
///   Notes            :      -Nil-
///   Revision History:
///   Name:           Date:        Description:
/// </summary>
namespace HellowWorld.Services
{

 

Class Comment:

Class comments will define the summary and detail of class (whether it is Interface / Abstract / Class)


/// <summary>
/// user related service methods goes here [ description ]
/// </summary>
public class UserServices : BaseService, IUserServices
{

 

Method Comment:

This comments helps developer to understand the detail of the method and it parameters definition.


/// <summary>
/// Login user with username and password [post method]
/// </summary>
/// <param name="request"></param>
/// <param name="errMsg"></param>
/// <returns></returns>
public LoginResult Login(LoginViewModel request, out string errMsg)
{

 

Single or multi-line comments?
It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer.

Summary:

Comments can be used to explain C# code, and to make it more readable. It can also be used to prevent execution when testing alternative code.