C# Syntax - Complete Guide
Basic C# Syntax Rules
C# syntax is similar to other C-style languages but has its own unique features. Understanding the basic syntax rules is essential for writing correct C# code.
C# is case-sensitive, uses semicolons to end statements, and curly braces to define code blocks. The language follows a structured approach with clear naming conventions.
Basic Program Structure
A simple C# program has the following structure:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// Your code goes here
Console.WriteLine("Hello, World!");
}
}
}
Hello, World!
Variables and Data Types
C# is a strongly-typed language, meaning variables must be declared with a specific type:
using System;
namespace VariablesExample
{
class Program
{
static void Main(string[] args)
{
// Variable declarations
int number = 10;
double price = 19.99;
string name = "John";
bool isTrue = true;
char grade = 'A';
// Display variables
Console.WriteLine("Number: " + number);
Console.WriteLine("Price: " + price);
Console.WriteLine("Name: " + name);
Console.WriteLine("Is True: " + isTrue);
Console.WriteLine("Grade: " + grade);
}
}
}
Number: 10 Price: 19.99 Name: John Is True: True Grade: A
Comments in C#
Comments are used to explain code and are ignored by the compiler:
using System;
namespace CommentsExample
{
class Program
{
static void Main(string[] args)
{
// This is a single-line comment
/*
This is a multi-line comment
that spans multiple lines
*/
Console.WriteLine("Hello, World!"); // Comment after code
/// <summary>
/// This is an XML documentation comment
/// </summary>
}
}
}
Hello, World!
Naming Conventions
C# follows specific naming conventions that improve readability and maintainability:
- **PascalCase** for class names, methods, and properties (e.g., `CustomerOrder`).
- **camelCase** for local variables and method parameters (e.g., `orderCount`).
- **UPPER_CASE** for constants (e.g., `MAX_SIZE`).
Consistent use of these conventions is considered a best practice in C# development.