C# Language Reference
The C# language is a modern, object-oriented programming language developed by Microsoft. It is a type-safe, component-oriented language that runs on the .NET Framework. C# is designed to offer the power of C++ with the ease of use of Visual Basic.
Core Concepts
C# is built around several fundamental programming concepts:
- Object-Oriented Programming (OOP): Encapsulation, Inheritance, and Polymorphism are first-class citizens in C#.
- Type Safety: C# enforces strict type checking to prevent common programming errors.
- Memory Management: The Common Language Runtime (CLR) handles memory allocation and deallocation through garbage collection, reducing the risk of memory leaks.
- Exception Handling: Robust mechanisms for handling runtime errors gracefully.
Key Language Features
Variables and Data Types
C# supports a rich set of built-in data types, including:
- Value Types: `int`, `float`, `double`, `bool`, `char`, `struct`, `enum`.
- Reference Types: `class`, `string`, `object`, `interface`, `delegate`, `array`.
Example:
int age = 30;
string name = "Alice";
bool isActive = true;
Control Flow
Control flow statements allow you to dictate the order in which code is executed.
- Conditional Statements: `if`, `else`, `switch`
- Looping Statements: `for`, `foreach`, `while`, `do-while`
- Branching Statements: `break`, `continue`, `return`, `goto`
Example:
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
Console.WriteLine($"{i} is even.");
}
}
Classes and Objects
Classes define the blueprints for objects, which are instances of those classes. They encapsulate data (fields) and behavior (methods).
public class Person
{
public string FirstName { get; set; }
public int Age { get; set; }
public void Greet()
{
Console.WriteLine($"Hello, my name is {FirstName} and I am {Age} years old.");
}
}
// Usage:
Person person1 = new Person { FirstName = "Bob", Age = 25 };
person1.Greet();
Methods
Methods are blocks of code that perform a specific task. They can accept parameters and return values.
public int Add(int a, int b)
{
return a + b;
}
int sum = Add(5, 3); // sum will be 8
Properties
Properties provide a flexible mechanism to read, write, or compute the value of a private field.
public class Product
{
private decimal _price;
public decimal Price
{
get { return _price; }
set
{
if (value >= 0)
{
_price = value;
}
else
{
throw new ArgumentOutOfRangeException("Price cannot be negative.");
}
}
}
}
Advanced Topics
C# offers a wide range of advanced features for building complex and efficient applications:
- Generics
- Asynchronous Programming (`async`/`await`)
- Language Integrated Query (LINQ)
- Pattern Matching
- Delegates and Events
- Reflection
For a complete list of C# language keywords and their usage, please refer to the C# Keywords page.