🎯 Рекомендуемые коллекции
Балансированные коллекции примеров кода из различных категорий, которые вы можете исследовать
Примеры C#
Основные примеры кода C# с разработкой .NET, современными возможностями C# и корпоративными паттернами
💻 C# Hello World csharp
🟢 simple
⭐
Базовая программа Hello World и фундаментальные концепции .NET с современным синтаксисом C#
⏱️ 10 min
🏷️ csharp, .net, beginner
Prerequisites:
Basic programming concepts
using System;
using System.Collections.Generic;
// 1. Basic Hello World
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
}
}
// 2. Hello World with variable
class Program
{
static void Main()
{
string message = "Hello, World!";
Console.WriteLine(message);
}
}
// 3. Hello World with function
class Program
{
static string GetGreeting()
{
return "Hello, World!";
}
static void Main()
{
Console.WriteLine(GetGreeting());
}
}
// 4. Hello World with parameters
class Program
{
static string GetGreeting(string name)
{
return $"Hello, {name}!";
}
static void Main()
{
Console.WriteLine(GetGreeting("World"));
Console.WriteLine(GetGreeting("C#"));
}
}
// 5. Hello World with class
class Greeter
{
private string _message;
public Greeter(string message = "Hello, World!")
{
_message = message;
}
public void DisplayGreeting()
{
Console.WriteLine(_message);
}
}
class Program
{
static void Main()
{
var greeter = new Greeter();
greeter.DisplayGreeting();
}
}
// 6. Hello World with user input
class Program
{
static void Main()
{
Console.Write("Enter your name: ");
string name = Console.ReadLine() ?? "World";
Console.WriteLine($"Hello, {name}!");
}
}
// 7. Hello World multiple times
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Hello, World! {i}");
}
}
}
// 8. Hello World with collection
class Program
{
static void Main()
{
var greetings = new List<string> { "Hello", "Bonjour", "Hola", "Ciao", "こんにちは" };
foreach (var greeting in greetings)
{
Console.WriteLine($"{greeting}, World!");
}
}
}
// 9. Hello World with dictionary
class Program
{
static void Main()
{
var greetings = new Dictionary<string, string>
{
{ "en", "Hello" },
{ "es", "Hola" },
{ "fr", "Bonjour" },
{ "de", "Hallo" },
{ "ja", "こんにちは" }
};
foreach (var greeting in greetings)
{
Console.WriteLine($"{greeting.Value}, World! ({greeting.Key})");
}
}
}
// 10. Hello World with exception handling
class Program
{
static void Main()
{
try
{
var numbers = new List<int> { 10, 0, 5 };
for (int i = 0; i < numbers.Count; i++)
{
Console.WriteLine($"100 / {numbers[i]} = {100 / numbers[i]}");
}
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
Console.WriteLine("Hello, Exception World!");
}
}
}
// Basic data types examples
class Program
{
static void Main()
{
// Primitive types
int integer = 42;
double floatingPoint = 3.14;
float singlePrecision = 3.14f;
decimal money = 99.99m;
boolean boolValue = true;
char character = '@';
string text = "Hello, C#";
Console.WriteLine($"Integer: {integer}, Type: {integer.GetType()}");
Console.WriteLine($"Double: {floatingPoint}, Type: {floatingPoint.GetType()}");
Console.WriteLine($"Float: {singlePrecision}, Type: {singlePrecision.GetType()}");
Console.WriteLine($"Decimal: {money}, Type: {money.GetType()}");
Console.WriteLine($"Boolean: {boolValue}, Type: {boolValue.GetType()}");
Console.WriteLine($"Char: {character}, Type: {character.GetType()}");
Console.WriteLine($"String: {text}, Type: {text.GetType()}");
// Nullable types
int? nullableInt = null;
DateTime? nullableDate = null;
Console.WriteLine($"Nullable int has value: {nullableInt.HasValue}");
Console.WriteLine($"Nullable date: {nullableDate ?? DateTime.MinValue}");
}
// Control flow examples
static void ControlFlowExamples()
{
int age = 18;
if (age >= 18)
{
Console.WriteLine("You are an adult");
}
else
{
Console.WriteLine("You are a minor");
}
// Switch expression (C# 8.0+)
string dayType = DateTime.Now.DayOfWeek switch
{
DayOfWeek.Saturday => "Weekend",
DayOfWeek.Sunday => "Weekend",
_ => "Weekday"
};
Console.WriteLine($"Today is a {dayType}");
// Loop examples
var fruits = new List<string> { "apple", "banana", "cherry" };
foreach (var fruit in fruits)
{
Console.WriteLine($"I like {fruit}");
}
// LINQ examples
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
var squaredNumbers = numbers.Select(n => n * n).ToList();
Console.WriteLine($"Even numbers: {string.Join(", ", evenNumbers)}");
Console.WriteLine($"Squared numbers: {string.Join(", ", squaredNumbers)}");
}
}
💻 Объектно-ориентированное программирование C# csharp
🟡 intermediate
⭐⭐⭐⭐
Продвинутые концепции ООП включая наследование, интерфейсы, дженерики и паттерны проектирования
⏱️ 40 min
🏷️ csharp, oop, design patterns, advanced
Prerequisites:
Basic C# syntax, Object-oriented concepts
using System;
using System.Collections.Generic;
// 1. Classes and Inheritance
public class Animal
{
public string Name { get; set; }
public int Age { get; set; }
protected Animal(string name, int age)
{
Name = name;
Age = age;
}
public virtual void MakeSound()
{
Console.WriteLine($"{Name} makes a sound");
}
public virtual void DisplayInfo()
{
Console.WriteLine($"{Name} is {Age} years old");
}
}
public class Dog : Animal
{
public string Breed { get; set; }
public Dog(string name, int age, string breed) : base(name, age)
{
Breed = breed;
}
public override void MakeSound()
{
Console.WriteLine($"{Name} barks: Woof!");
}
public void WagTail()
{
Console.WriteLine($"{Name} is wagging its tail");
}
}
public class Cat : Animal
{
public bool IsIndoor { get; set; }
public Cat(string name, int age, bool isIndoor) : base(name, age)
{
IsIndoor = isIndoor;
}
public override void MakeSound()
{
Console.WriteLine($"{Name} meows: Meow!");
}
public void Purr()
{
Console.WriteLine($"{Name} is purring");
}
}
// 2. Interfaces
public interface IShape
{
double CalculateArea();
double CalculatePerimeter();
void DisplayShapeInfo();
}
public interface IMovable
{
void Move(int distanceX, int distanceY);
}
public class Circle : IShape
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
public double CalculateArea()
{
return Math.PI * Radius * Radius;
}
public double CalculatePerimeter()
{
return 2 * Math.PI * Radius;
}
public void DisplayShapeInfo()
{
Console.WriteLine($"Circle - Radius: {Radius}, Area: {CalculateArea():F2}");
}
}
public class Rectangle : IShape, IMovable
{
public double Width { get; set; }
public double Height { get; set; }
public double X { get; private set; }
public double Y { get; private set; }
public Rectangle(double width, double height, double x = 0, double y = 0)
{
Width = width;
Height = height;
X = x;
Y = y;
}
public double CalculateArea()
{
return Width * Height;
}
public double CalculatePerimeter()
{
return 2 * (Width + Height);
}
public void DisplayShapeInfo()
{
Console.WriteLine($"Rectangle - Width: {Width}, Height: {Height}, Area: {CalculateArea():F2}");
}
public void Move(int distanceX, int distanceY)
{
X += distanceX;
Y += distanceY;
Console.WriteLine($"Rectangle moved to ({X}, {Y})");
}
}
// 3. Abstract Classes
public abstract class Vehicle
{
public string Brand { get; set; }
public string Model { get; set; }
public int Year { get; set; }
protected Vehicle(string brand, string model, int year)
{
Brand = brand;
Model = model;
Year = year;
}
public abstract void Start();
public abstract void Stop();
public virtual void DisplayInfo()
{
Console.WriteLine($"{Year} {Brand} {Model}");
}
}
public class Car : Vehicle
{
public int NumberOfDoors { get; set; }
public Car(string brand, string model, int year, int numberOfDoors)
: base(brand, model, year)
{
NumberOfDoors = numberOfDoors;
}
public override void Start()
{
Console.WriteLine($"{Brand} {Model} engine started");
}
public override void Stop()
{
Console.WriteLine($"{Brand} {Model} engine stopped");
}
public void OpenTrunk()
{
Console.WriteLine("Trunk opened");
}
}
// 4. Generics
public class GenericContainer<T>
{
private T _item;
public GenericContainer(T item)
{
_item = item;
}
public T GetItem()
{
return _item;
}
public void SetItem(T item)
{
_item = item;
}
public override string ToString()
{
return $"Container with: {_item}";
}
}
public class Calculator
{
public T Add<T>(T a, T b) where T : struct
{
if (a is int intA && b is int intB)
return (T)(object)(intA + intB);
if (a is double doubleA && b is double doubleB)
return (T)(object)(doubleA + doubleB);
throw new NotSupportedException("Only int and double operations are supported");
}
}
// 5. Generic Repository Pattern
public interface IRepository<T> where T : class
{
T GetById(int id);
IEnumerable<T> GetAll();
void Add(T entity);
void Update(T entity);
void Delete(int id);
}
public class InMemoryRepository<T> : IRepository<T> where T : class
{
private readonly Dictionary<int, T> _storage = new();
public T GetById(int id)
{
return _storage.TryGetValue(id, out var entity) ? entity : null;
}
public IEnumerable<T> GetAll()
{
return _storage.Values;
}
public void Add(T entity)
{
int id = _storage.Count + 1;
_storage[id] = entity;
}
public void Update(T entity)
{
// In a real implementation, you'd update by entity ID
Console.WriteLine($"Entity updated: {entity}");
}
public void Delete(int id)
{
_storage.Remove(id);
}
}
// 6. Design Patterns - Singleton
public sealed class Logger
{
private static readonly Lazy<Logger> _instance = new Lazy<Logger>(() => new Logger());
private readonly List<string> _logs = new List<string>();
private Logger()
{
}
public static Logger Instance => _instance.Value;
public void Log(string message)
{
string logEntry = $"{DateTime.Now}: {message}";
_logs.Add(logEntry);
Console.WriteLine(logEntry);
}
public void PrintAllLogs()
{
Console.WriteLine("=== All Logs ===");
foreach (var log in _logs)
{
Console.WriteLine(log);
}
}
}
// 7. Factory Pattern
public interface IPaymentProcessor
{
void ProcessPayment(decimal amount);
}
public class CreditCardProcessor : IPaymentProcessor
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($"Processing credit card payment of ${amount}");
}
}
public class PayPalProcessor : IPaymentProcessor
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($"Processing PayPal payment of ${amount}");
}
}
public static class PaymentProcessorFactory
{
public static IPaymentProcessor CreateProcessor(string paymentType)
{
return paymentType.ToLower() switch
{
"creditcard" => new CreditCardProcessor(),
"paypal" => new PayPalProcessor(),
_ => throw new ArgumentException($"Unknown payment type: {paymentType}")
};
}
}
// 8. Observer Pattern
public interface IObserver<T>
{
void Update(T data);
}
public interface ISubject<T>
{
void Subscribe(IObserver<T> observer);
void Unsubscribe(IObserver<T> observer);
void Notify(T data);
}
public class WeatherStation : ISubject<float>
{
private readonly List<IObserver<float>> _observers = new List<IObserver<float>>();
private float _temperature;
public float Temperature
{
get => _temperature;
set
{
_temperature = value;
Notify(_temperature);
}
}
public void Subscribe(IObserver<float> observer)
{
_observers.Add(observer);
}
public void Unsubscribe(IObserver<float> observer)
{
_observers.Remove(observer);
}
public void Notify(float data)
{
foreach (var observer in _observers)
{
observer.Update(data);
}
}
}
public class TemperatureDisplay : IObserver<float>
{
private readonly string _name;
public TemperatureDisplay(string name)
{
_name = name;
}
public void Update(float temperature)
{
Console.WriteLine($"{_name} display shows: {temperature}°C");
}
}
// Example usage
class Program
{
static void Main()
{
// Inheritance demo
var dog = new Dog("Buddy", 3, "Golden Retriever");
dog.DisplayInfo();
dog.MakeSound();
dog.WagTail();
// Interface demo
var circle = new Circle(5.0);
circle.DisplayShapeInfo();
var rectangle = new Rectangle(4.0, 6.0);
rectangle.DisplayShapeInfo();
rectangle.Move(10, 15);
// Generics demo
var intContainer = new GenericContainer<int>(42);
var stringContainer = new GenericContainer<string>("Hello Generics!");
Console.WriteLine(intContainer);
Console.WriteLine(stringContainer);
// Singleton demo
var logger = Logger.Instance;
logger.Log("Application started");
logger.Log("User logged in");
// Factory demo
var creditCardProcessor = PaymentProcessorFactory.CreateProcessor("creditcard");
creditCardProcessor.ProcessPayment(99.99m);
// Observer demo
var weatherStation = new WeatherStation();
var display1 = new TemperatureDisplay("Living Room");
var display2 = new TemperatureDisplay("Kitchen");
weatherStation.Subscribe(display1);
weatherStation.Subscribe(display2);
weatherStation.Temperature = 25.5f;
weatherStation.Temperature = 26.0f;
}
}
💻 Современные возможности C# csharp
🔴 complex
⭐⭐⭐⭐
Современные возможности C# 8-11 включая records, pattern matching и асинхронное программирование
⏱️ 45 min
🏷️ csharp, modern c#, async, advanced, csharp9, csharp10, csharp11
Prerequisites:
Advanced C#, .NET Core/.NET 5+, Asynchronous programming concepts
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// 1. Records (C# 9.0+)
// Positional record
public record Person(string FirstName, string LastName, int Age);
// Record with methods
public record Employee(int Id, string Name, decimal Salary)
{
public decimal AnnualBonus { get; init; } = 0;
public decimal TotalCompensation => Salary + AnnualBonus;
public virtual void GiveRaise(decimal amount)
{
Console.WriteLine($"{Name} got a raise of ${amount}");
}
}
// Record inheritance
public record Manager(int Id, string Name, decimal Salary, string Department)
: Employee(Id, Name, Salary)
{
public override void GiveRaise(decimal amount)
{
Console.WriteLine($"Manager {Name} in {Department} got a raise of ${amount}");
}
}
// 2. Pattern Matching (C# 8.0+)
public class PatternMatching
{
public static string GetDescription(object value)
{
return value switch
{
null => "Null value",
int i when i < 0 => "Negative integer",
int i when i > 0 => "Positive integer",
int i => "Zero",
string s when string.IsNullOrEmpty(s) => "Empty string",
string s when s.Length > 10 => "Long string",
string s => $"String: {s}",
DateTime dt when dt > DateTime.Now => "Future date",
DateTime dt when dt < DateTime.Now => "Past date",
DateTime dt => "Today",
Person p when p.Age < 18 => $"{p.FirstName} is a minor",
Person p => $"{p.FirstName} is {p.Age} years old",
_ => "Unknown type"
};
}
public static decimal CalculateDiscount(Product product)
{
return product switch
{
{ Category: "Electronics", Price: > 1000 } => product.Price * 0.1m,
{ Category: "Electronics", Price: > 500 } => product.Price * 0.05m,
{ Category: "Books", Price: var price } when price < 20 => price * 0.15m,
{ Category: "Clothing", InStock: false } => 0m,
{ Price: var price } when price > 100 => price * 0.2m,
_ => 0m
};
}
}
public class Product
{
public string Name { get; set; } = "";
public string Category { get; set; } = "";
public decimal Price { get; set; }
public bool InStock { get; set; } = true;
}
// 3. Nullable Reference Types (C# 8.0+)
#nullable enable
public class UserService
{
private readonly Dictionary<int, User> _users = new();
public User? GetUserById(int id)
{
return _users.TryGetValue(id, out var user) ? user : null;
}
public string GetUserEmail(int id)
{
var user = GetUserById(id);
return user?.Email ?? throw new InvalidOperationException("User not found");
}
public void PrintUserName(int id)
{
var user = GetUserById(id);
if (user != null)
{
Console.WriteLine($"User: {user.Name}");
}
else
{
Console.WriteLine("User not found");
}
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string? Email { get; set; }
public List<string>? Tags { get; set; }
}
// 4. Async Programming (C# 8.0+)
public class AsyncService
{
public async Task<string> FetchDataAsync(string url)
{
Console.WriteLine($"Starting fetch from {url}");
// Simulate async operation
await Task.Delay(1000);
Console.WriteLine($"Completed fetch from {url}");
return $"Data from {url}";
}
public async Task<IEnumerable<string>> FetchMultipleUrlsAsync(IEnumerable<string> urls)
{
var tasks = urls.Select(url => FetchDataAsync(url));
var results = await Task.WhenAll(tasks);
return results;
}
public async IAsyncEnumerable<string> StreamDataAsync(IEnumerable<int> numbers)
{
foreach (var number in numbers)
{
await Task.Delay(100); // Simulate async work
yield return $"Processed: {number}";
}
}
public async Task ProcessDataStreamAsync()
{
var numbers = Enumerable.Range(1, 10);
await foreach (var result in StreamDataAsync(numbers))
{
Console.WriteLine(result);
}
}
}
// 5. Expression-bodied members (C# 6.0+)
public class Calculator
{
public double Add(double a, double b) => a + b;
public double Subtract(double a, double b) => a - b;
public double Multiply(double a, double b) => a * b;
public double Divide(double a, double b) => b != 0 ? a / b : throw new DivideByZeroException();
public static double Pi => Math.PI;
public static double E => Math.E;
}
// 6. Tuples and deconstruction (C# 7.0+)
public class TupleExamples
{
public static (int Min, int Max, double Average) CalculateStats(IEnumerable<int> numbers)
{
var list = numbers.ToList();
return (list.Min(), list.Max(), list.Average());
}
public static void DeconstructionExample()
{
var (min, max, avg) = CalculateStats(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
Console.WriteLine($"Min: {min}, Max: {max}, Avg: {avg}");
}
public static (string FirstName, string LastName) ParseName(string fullName)
{
var parts = fullName.Split(' ', StringSplitOptions.RemoveEmptyEntries);
return (parts.Length > 0 ? parts[0] : "", parts.Length > 1 ? parts[1] : "");
}
}
// 7. Local functions (C# 7.0+)
public class LocalFunctionExamples
{
public static int Factorial(int n)
{
int ComputeFactorial(int x)
{
return x <= 1 ? 1 : x * ComputeFactorial(x - 1);
}
return ComputeFactorial(n);
}
public static bool IsPalindrome(string text)
{
bool CheckPalindrome(string s, int left, int right)
{
return left >= right || s[left] == s[right] && CheckPalindrome(s, left + 1, right - 1);
}
var cleanText = string.Concat(text.Where(char.IsLetterOrDigit)).ToLower();
return CheckPalindrome(cleanText, 0, cleanText.Length - 1);
}
}
// 8. Switch expressions (C# 8.0+)
public class SwitchExpressionExamples
{
public static string GetDayType(DayOfWeek day) => day switch
{
DayOfWeek.Saturday => "Weekend",
DayOfWeek.Sunday => "Weekend",
_ => "Weekday"
};
public static decimal CalculateTax(decimal amount, string state) => state.ToUpper() switch
{
"CA" => amount * 0.0875m,
"NY" => amount * 0.08m,
"TX" => amount * 0.0625m,
"FL" => amount * 0.06m,
_ => 0m
};
public static string GetGradeLetter(int score) => score switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
>= 60 => "D",
_ => "F"
};
}
// 9. Using declarations (C# 8.0+)
public class UsingDeclarationExamples
{
public static async Task ProcessFilesAsync()
{
await foreach (var line in ReadLinesAsync("example.txt"))
{
Console.WriteLine($"Read: {line}");
}
}
private static async IAsyncEnumerable<string> ReadLinesAsync(string filename)
{
using var reader = new StreamReader(filename);
string? line;
while ((line = await reader.ReadLineAsync()) != null)
{
yield return line;
}
}
}
// 10. Static local functions (C# 8.0+)
public class StaticLocalFunctionExample
{
public static int Calculate(int x, int y)
{
static int Add(int a, int b) => a + b;
static int Multiply(int a, int b) => a * b;
return Add(x, y) + Multiply(x, y);
}
}
// 11. Target-typed new expressions (C# 9.0+)
public class TargetTypedNew
{
private readonly List<string> _names = new();
private readonly Dictionary<int, string> _dictionary = new();
public void AddName(string name) => _names.Add(name);
public int Count => _names.Count;
}
// 12. Top-level statements (C# 9.0+)
// This file itself demonstrates top-level statements
// Example usage
class Program
{
static async Task Main()
{
// Records demo
var person = new Person("John", "Doe", 30);
Console.WriteLine(person);
var employee = new Employee(1, "Jane Smith", 75000m) { AnnualBonus = 5000m };
Console.WriteLine($"Total compensation: {employee.TotalCompensation:C}");
// Pattern matching demo
Console.WriteLine(PatternMatching.GetDescription(person));
var product = new Product { Name = "Laptop", Category = "Electronics", Price = 1200m, InStock = true };
decimal discount = PatternMatching.CalculateDiscount(product);
Console.WriteLine($"Discount: ${discount}");
// Tuples demo
TupleExamples.DeconstructionExample();
var (firstName, lastName) = TupleExamples.ParseName("John Doe");
Console.WriteLine($"First: {firstName}, Last: {lastName}");
// Async demo
var asyncService = new AsyncService();
string data = await asyncService.FetchDataAsync("https://api.example.com");
Console.WriteLine(data);
var urls = new[] { "https://api1.com", "https://api2.com", "https://api3.com" };
var results = await asyncService.FetchMultipleUrlsAsync(urls);
foreach (var result in results)
{
Console.WriteLine(result);
}
await asyncService.ProcessDataStreamAsync();
// Switch expressions demo
Console.WriteLine($"Today is a {SwitchExpressionExamples.GetDayType(DateTime.Now.DayOfWeek)}");
Console.WriteLine($"Grade for 85: {SwitchExpressionExamples.GetGradeLetter(85)}");
// Local functions demo
Console.WriteLine($"5! = {LocalFunctionExamples.Factorial(5)}");
Console.WriteLine($"'racecar' is palindrome: {LocalFunctionExamples.IsPalindrome("racecar")}");
// Using declarations demo
// Uncomment to test with actual file
// await UsingDeclarationExamples.ProcessFilesAsync();
Console.WriteLine("Modern C# features demonstration completed!");
}
}