C# Language Documentation
Welcome to the comprehensive documentation for the C# programming language. C# is a modern, object-oriented, and type-safe programming language developed by Microsoft. It is widely used for building a variety of applications, from desktop and web applications to mobile apps and games.
Getting Started
To begin your journey with C#, you'll need to set up your development environment. The most common way is to use Visual Studio or Visual Studio Code with the C# extension.
Prerequisites:
- .NET SDK installed.
- A code editor (Visual Studio, VS Code).
Your First C# Program
Create a new console application project and write the following code:
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
This simple program outputs "Hello, World!" to the console.
Language Basics
Variables and Data Types
C# is a strongly-typed language. Variables must be declared with a specific data type.
int number = 10; // Integer
double pi = 3.14159; // Floating-point number
string message = "Hello"; // String
bool isTrue = true; // Boolean
Operators
C# supports a wide range of operators for arithmetic, comparison, logical operations, and more.
Arithmetic Operators: +
, -
, *
, /
, %
Comparison Operators: ==
, !=
, <
, >
, <=
, >=
Logical Operators: &&
(AND), ||
(OR), !
(NOT)
Control Flow
Control flow statements allow you to direct the execution of your program.
if (number > 5)
{
Console.WriteLine("Number is greater than 5.");
}
else if (number == 5)
{
Console.WriteLine("Number is 5.");
}
else
{
Console.WriteLine("Number is less than 5.");
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Iteration: {i}");
}
while (isTrue)
{
Console.WriteLine("This loop will continue indefinitely.");
isTrue = false; // Prevent infinite loop in example
}
Methods
Methods are blocks of code that perform a specific task.
public int Add(int a, int b)
{
return a + b;
}
public void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
Classes and Objects
Classes are blueprints for creating objects. Objects are instances of classes.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
// Creating an object
Person person1 = new Person("Alice", 30);
person1.DisplayInfo();
Advanced Topics
Asynchronous Programming
The async
and await
keywords simplify asynchronous programming, allowing your applications to remain responsive.
public async Task LoadDataAsync()
{
Console.WriteLine("Starting data load...");
await Task.Delay(2000); // Simulate network latency
Console.WriteLine("Data loaded.");
}
LINQ (Language Integrated Query)
LINQ provides a powerful and flexible way to query data from various sources.
List<int> numbers = new List<int> { 5, 1, 4, 2, 8, 3, 7, 6 };
var evenNumbers = numbers.Where(n => n % 2 == 0).OrderBy(n => n);
Console.WriteLine("Even numbers: ");
foreach (var num in evenNumbers)
{
Console.Write($"{num} ");
}
Console.WriteLine();
Language Features
C# continuously evolves with new features to enhance developer productivity and code expressiveness.
Records
Records are a new class type for primarily data-holding scenarios, offering immutability and value-based equality.
public record Customer(string Name, int Id);
Customer cust1 = new Customer("Bob", 101);
Customer cust2 = new Customer("Bob", 101);
Console.WriteLine(cust1 == cust2); // Output: True
Pattern Matching
Pattern matching allows you to check types and extract data from objects in a concise way.
object data = "Some Text";
if (data is string str)
{
Console.WriteLine($"It's a string: {str.ToUpper()}");
}
Best Practices
Adhering to best practices ensures code maintainability, readability, and robustness.
- Use meaningful names for variables, methods, and classes.
- Follow C# naming conventions (PascalCase for public members, camelCase for local variables).
- Write clear and concise code.
- Comment complex logic.
- Embrace object-oriented principles like encapsulation, inheritance, and polymorphism.
- Utilize LINQ for data manipulation where appropriate.
- Handle exceptions gracefully.
- Keep methods short and focused on a single task.