C# Basic Syntax

Microsoft Developer Network - Documentation

Understanding C# Basic Syntax

This document provides a fundamental overview of the C# programming language's basic syntax. Mastering these building blocks is crucial for writing efficient and readable C# code.

Comments

Comments are used to explain code and are ignored by the compiler. C# supports single-line and multi-line comments.


// This is a single-line comment
/* This is a
   multi-line comment */
/// <summary>
/// This is an XML documentation comment.
/// </summary>
        

Keywords and Identifiers

Keywords are reserved words with special meanings in C# (e.g., class, namespace, public, int). Identifiers are names given to program elements like variables, classes, and methods. They must start with a letter or underscore and can contain letters, numbers, and underscores. Identifiers are case-sensitive.

Basic Structure: Namespaces and Classes

C# code is organized into namespaces, which help prevent naming conflicts. Each executable program must contain at least one class. A class is a blueprint for creating objects.


namespace MyFirstApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Code execution starts here
            System.Console.WriteLine("Hello, C# World!");
        }
    }
}
        

Variables and Data Types

Variables are used to store data. C# is a statically-typed language, meaning each variable must have a declared data type.


int age = 30;
double price = 19.99;
bool isComplete = false;
string name = "Alice";
        

Operators

Operators are symbols that perform operations on variables and values. Common operators include:


int a = 10;
int b = 5;
int sum = a + b; // sum will be 15
bool isEqual = (a == b); // isEqual will be false
        

Control Flow Statements

These statements control the order in which code is executed.

Conditional Statements (if, else, switch)


if (age >= 18) {
    System.Console.WriteLine("Adult");
} else {
    System.Console.WriteLine("Minor");
}
        

Looping Statements (for, while, foreach)


for (int i = 0; i < 5; i++) {
    System.Console.WriteLine(i);
}

foreach (char c in name) {
    System.Console.WriteLine(c);
}
        

Methods (Functions)

Methods are blocks of code that perform a specific task. They help in code modularity and reusability.


public static int Add(int num1, int num2)
{
    return num1 + num2;
}

int result = Add(5, 3); // result will be 8
        

This covers the most fundamental aspects of C# syntax. Continue exploring data types, control structures, and object-oriented programming concepts to build more complex applications.