Microsoft Developer Network - Documentation
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 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 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.
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 are used to store data. C# is a statically-typed language, meaning each variable must have a declared data type.
int: Whole numbers (e.g., 10, -5)double: Floating-point numbers (e.g., 3.14, -0.5)bool: True or false valuesstring: Sequence of characters (e.g., "Hello")char: Single character (e.g., 'A')
int age = 30;
double price = 19.99;
bool isComplete = false;
string name = "Alice";
Operators are symbols that perform operations on variables and values. Common operators include:
+, -, *, /, %==, !=, >, <, >=, <=&& (AND), || (OR), ! (NOT)=, +=, -=, etc.
int a = 10;
int b = 5;
int sum = a + b; // sum will be 15
bool isEqual = (a == b); // isEqual will be false
These statements control the order in which code is executed.
if, else, switch)
if (age >= 18) {
System.Console.WriteLine("Adult");
} else {
System.Console.WriteLine("Minor");
}
for, while, foreach)
for (int i = 0; i < 5; i++) {
System.Console.WriteLine(i);
}
foreach (char c in name) {
System.Console.WriteLine(c);
}
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.