How to write single-line comments in C#?

Single-line comments in C# are created using two forward slashes (//). Everything after the // on that line is treated as a comment and is ignored by the compiler. These comments are useful for explaining code, adding notes, or temporarily disabling a line of code.

Syntax

Following is the syntax for single-line comments in C# −

// This is a single-line comment
int variable = 10; // Comment at the end of a line

Using Single-Line Comments for Code Documentation

Example

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         // Display greeting message
         Console.WriteLine("Hello World");
         
         // Declare and initialize variables
         int age = 25;
         string name = "John";
         
         // Display user information
         Console.WriteLine("Name: " + name + ", Age: " + age);
      }
   }
}

The output of the above code is −

Hello World
Name: John, Age: 25

Using Comments to Disable Code Temporarily

Example

using System;

class Calculator {
   static void Main() {
      int a = 10;
      int b = 5;
      
      // Perform basic arithmetic operations
      Console.WriteLine("Addition: " + (a + b));
      Console.WriteLine("Subtraction: " + (a - b));
      
      // Temporarily disable multiplication
      // Console.WriteLine("Multiplication: " + (a * b));
      
      Console.WriteLine("Division: " + (a / b));
   }
}

The output of the above code is −

Addition: 15
Subtraction: 5
Division: 2

Comments at Different Positions

Example

using System;

class CommentExample {
   static void Main() {
      // Comment at the beginning of a line
      int x = 100;
      
      int y = 200; // Comment at the end of a line
      
      // Multiple single-line comments
      // can be used together to create
      // a block of explanatory text
      
      Console.WriteLine("Sum: " + (x + y)); // Result comment
   }
}

The output of the above code is −

Sum: 300

Conclusion

Single-line comments in C# use the // syntax and are essential for code documentation and temporarily disabling code. They can be placed at the beginning of a line or at the end of a code statement, making your code more readable and maintainable.

Updated on: 2026-03-17T07:04:35+05:30

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements