Skip to main content

C# Syntax

Introduction​

When learning any programming language, understanding its syntax is the essential first step. C# syntax defines the rules for how we write code in the C# language. Think of it as the grammar of the language—it determines how we structure our statements, declare variables, use operators, and organize our code.

In this guide, we'll explore C# syntax fundamentals that every beginner should know. We'll cover the basic structure of a C# program, how to write statements, declare variables, add comments, and follow best practices for writing clean, readable code.

Basic Program Structure​

Every C# program needs a specific structure to run correctly. Here's the simplest C# program:

csharp
using System;

namespace MyFirstProgram
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}

Output:

Hello, World!

Let's break down this structure:

  1. using System; - This is a directive that tells the compiler to include the System namespace, which contains fundamental classes and base types.

  2. namespace MyFirstProgram - A namespace organizes your code and prevents naming conflicts.

  3. class Program - Classes are the building blocks of C# programs and contain data and methods.

  4. static void Main(string[] args) - The Main method is the entry point of a C# application.

  5. Console.WriteLine("Hello, World!"); - A statement that displays text in the console.

Statements and Expressions​

In C#, statements are instructions that perform actions. Almost all statements in C# end with a semicolon (;).

csharp
// This is a statement
Console.WriteLine("This is a statement!");

// Multiple statements
int x = 5;
int y = 10;
int sum = x + y;
Console.WriteLine("The sum is: " + sum);

Output:

This is a statement!
The sum is: 15

An expression is a piece of code that evaluates to a value. Expressions can be part of statements.

csharp
int result = 5 + 3 * 2;  // Expression: 5 + 3 * 2
Console.WriteLine(result);

Output:

11

Variables and Data Types​

Variables store data that can be used throughout your program. In C#, you must declare a variable's type before using it.

csharp
// Variable declarations
int age = 25; // Integer
double price = 19.99; // Double-precision floating point
string name = "John Smith"; // String
bool isStudent = true; // Boolean
char grade = 'A'; // Character

// Displaying variables
Console.WriteLine($"Name: {name}, Age: {age}");
Console.WriteLine($"Price: ${price}, Grade: {grade}");
Console.WriteLine($"Is student: {isStudent}");

Output:

Name: John Smith, Age: 25
Price: $19.99, Grade: A
Is student: True

Comments​

Comments help you document your code and make it more understandable. C# supports both single-line and multi-line comments.

csharp
// This is a single-line comment

/*
This is a
multi-line comment
*/

/// <summary>
/// XML comments are used for documentation
/// </summary>
public void DocumentedMethod()
{
// Method implementation
}

Operators​

Operators perform operations on variables and values.

csharp
// Arithmetic operators
int a = 10, b = 3;
Console.WriteLine($"a + b = {a + b}"); // Addition
Console.WriteLine($"a - b = {a - b}"); // Subtraction
Console.WriteLine($"a * b = {a * b}"); // Multiplication
Console.WriteLine($"a / b = {a / b}"); // Division
Console.WriteLine($"a % b = {a % b}"); // Modulus (remainder)

// Comparison operators
Console.WriteLine($"a == b: {a == b}"); // Equal to
Console.WriteLine($"a != b: {a != b}"); // Not equal to
Console.WriteLine($"a > b: {a > b}"); // Greater than

// Logical operators
bool x = true, y = false;
Console.WriteLine($"x && y: {x && y}"); // Logical AND
Console.WriteLine($"x || y: {x || y}"); // Logical OR
Console.WriteLine($"!x: {!x}"); // Logical NOT

Output:

a + b = 13
a - b = 7
a * b = 30
a / b = 3
a % b = 1
a == b: False
a != b: True
a > b: True
x && y: False
x || y: True
!x: False

Control Structures​

C# offers various control structures to control the flow of your program.

If-Else Statements​

csharp
int temperature = 25;

if (temperature > 30)
{
Console.WriteLine("It's hot outside!");
}
else if (temperature > 20)
{
Console.WriteLine("It's a nice day!");
}
else
{
Console.WriteLine("It's cold outside!");
}

Output:

It's a nice day!

Loops​

csharp
// For loop
Console.WriteLine("For loop:");
for (int i = 1; i <= 3; i++)
{
Console.WriteLine($"Iteration {i}");
}

// While loop
Console.WriteLine("\nWhile loop:");
int counter = 1;
while (counter <= 3)
{
Console.WriteLine($"Count: {counter}");
counter++;
}

// Foreach loop
Console.WriteLine("\nForeach loop:");
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}

Output:

For loop:
Iteration 1
Iteration 2
Iteration 3

While loop:
Count: 1
Count: 2
Count: 3

Foreach loop:
Apple
Banana
Cherry

Methods​

Methods are blocks of code that perform specific tasks. They help organize code and promote reusability.

csharp
using System;

namespace MethodsExample
{
class Program
{
static void Main(string[] args)
{
// Call methods
Greet("Alice");
int result = Add(5, 3);
Console.WriteLine($"5 + 3 = {result}");
}

// Method that returns void
static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}

// Method that returns an int
static int Add(int a, int b)
{
return a + b;
}
}
}

Output:

Hello, Alice!
5 + 3 = 8

Real-World Example: Simple Calculator​

Let's create a simple calculator program to apply what we've learned:

csharp
using System;

namespace SimpleCalculator
{
class Program
{
static void Main(string[] args)
{
// Display welcome message
Console.WriteLine("Simple Calculator");
Console.WriteLine("----------------");

// Get first number
Console.Write("Enter first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());

// Get second number
Console.Write("Enter second number: ");
double num2 = Convert.ToDouble(Console.ReadLine());

// Get operation
Console.Write("Enter operation (+, -, *, /): ");
char operation = Convert.ToChar(Console.ReadLine());

// Perform calculation
double result = 0;
bool isValidOperation = true;

switch (operation)
{
case '+':
result = Add(num1, num2);
break;
case '-':
result = Subtract(num1, num2);
break;
case '*':
result = Multiply(num1, num2);
break;
case '/':
// Check for division by zero
if (num2 != 0)
{
result = Divide(num1, num2);
}
else
{
Console.WriteLine("Error: Cannot divide by zero!");
isValidOperation = false;
}
break;
default:
Console.WriteLine("Error: Invalid operation!");
isValidOperation = false;
break;
}

// Display result
if (isValidOperation)
{
Console.WriteLine($"Result: {num1} {operation} {num2} = {result}");
}
}

// Calculator methods
static double Add(double a, double b) => a + b;
static double Subtract(double a, double b) => a - b;
static double Multiply(double a, double b) => a * b;
static double Divide(double a, double b) => a / b;
}
}

Sample Execution:

Simple Calculator
----------------
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): *
Result: 10 * 5 = 50

This calculator example demonstrates:

  • Getting user input
  • Type conversion
  • Control flow with switch statements
  • Method definitions and calls
  • Error handling for invalid operations

Best Practices for C# Syntax​

  1. Use meaningful names: Choose descriptive names for variables, methods, and classes.

    csharp
    // Good
    int studentAge = 21;

    // Not as good
    int x = 21;
  2. Follow C# naming conventions:

    • Use camelCase for local variables and parameters
    • Use PascalCase for methods, classes, and properties
    • Use _camelCase for private fields
  3. Add appropriate comments: Comment your code, but don't overdo it. Focus on why, not what.

  4. Use consistent indentation: Properly indent your code to enhance readability.

  5. One statement per line: Keep your code readable by putting each statement on its own line.

  6. Use braces properly: Always use braces for control structures, even for single-line statements.

Summary​

In this guide, we've covered the fundamental syntax elements of C#:

  • The basic structure of a C# program
  • Statements and expressions
  • Variables and data types
  • Comments and documentation
  • Operators for different operations
  • Control structures like if-else statements and loops
  • Methods for organizing code
  • A practical calculator example
  • Best practices for writing clean C# code

Understanding these syntax fundamentals provides a solid foundation for building your C# programming skills. Remember that practice is key to mastering any programming language—try writing your own programs and experimenting with different syntax elements.

Additional Resources and Exercises​

Resources​

Exercises​

  1. Variable Practice: Create variables of different types and perform operations on them.
  2. Math Calculator: Extend our calculator to include more operations like exponentiation, square root, etc.
  3. Temperature Converter: Create a program that converts between Fahrenheit and Celsius.
  4. Word Counter: Write a program that counts the words in a user-inputted sentence.
  5. Number Guesser: Create a game where users try to guess a random number, with hints if they're too high or too low.

Keep practicing and experimenting with the syntax you've learned, and you'll become proficient in C# programming in no time!



If you spot any mistakes on this website, please let me know at feedback@compilenrun.com. I’d greatly appreciate your feedback! :)