Шпаргалка по C#

1. Базовый синтаксис

Структура программы

using System;

class Program
{<br> static void Main()<br> {<br> Console.WriteLine("Привет, мир!");<br> }
}

Переменные

int age = 20;
double price = 99.5;
char letter = 'A';
string name = "Иван";
bool isStudent = true;

Константы

const double Pi = 3.14159;

Ввод и вывод

string s = Console.ReadLine();
Console.WriteLine("Текст");
Console.Write("Без переноса");

Преобразование типов

int x = int.Parse("123");
double y = Convert.ToDouble("12.5");
string text = x.ToString();

2. Условные конструкции

if / else

if (x > 0)
{<br> Console.WriteLine("Положительное");<br>}
else if (x < 0)
{<br> Console.WriteLine("Отрицательное");<br>}
else
{<br> Console.WriteLine("Ноль");<br>}

switch

switch (day)
{<br> case 1:<br> Console.WriteLine("Понедельник");<br> break;<br> case 2:<br> Console.WriteLine("Вторник");<br> break;<br> default:<br> Console.WriteLine("Неизвестно");<br> break;<br>}

Тернарный оператор

string result = x > 0 ? "Плюс" : "Не плюс";

3. Циклы

for

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

while

int i = 0;
while (i < 5)
{<br> Console.WriteLine(i);<br> i++;<br>}

do while

int i = 0;
do
{<br> Console.WriteLine(i);<br> i++;<br>} while (i < 5);

foreach

int[] arr = { 1, 2, 3 };
foreach (int item in arr)
{<br> Console.WriteLine(item);<br>}

4. Массивы

int[] nums = { 10, 20, 30 };
Console.WriteLine(nums[0]);
nums[1] = 99;
Console.WriteLine(nums.Length);

Двумерный массив:

int[,] matrix = {<br> {1, 2},
{3, 4}
};

Console.WriteLine(matrix[0, 1]); // 2

5. Методы

static int Sum(int a, int b)
{<br> return a + b;<br>}

Вызов:

int result = Sum(3, 4);

Метод без возврата:

static void PrintHello()
{<br> Console.WriteLine("Hello");<br>}

Параметры по умолчанию:

static void Greet(string name = "Гость")
{<br> Console.WriteLine($"Привет, {name}");
}

6. Классы и объекты

Класс

class Person
{<br> public string Name;<br> public int Age;<br><br> public void SayHello()<br> {<br> Console.WriteLine($"Привет, я {Name}");
}
}

Создание объекта

Person p = new Person();
p.Name = "Анна";
p.Age = 18;
p.SayHello();

7. Свойства

class Person
{<br> public string Name { get; set; }
public int Age { get; set; }
}

С ограничением:

class Person
{<br> private int age;<br><br> public int Age<br> {<br> get { return age; }
set
{<br> if (value >= 0)<br> age = value;<br> }
}
}

8. Конструкторы

class Person
{<br> public string Name;<br> public int Age;<br><br> public Person(string name, int age)<br> {<br> Name = name;<br> Age = age;<br> }
}
Person p = new Person("Иван", 20);

9. Наследование

class Animal
{<br> public void Eat()<br> {<br> Console.WriteLine("Ест");<br> }
}

class Dog : Animal
{<br> public void Bark()<br> {<br> Console.WriteLine("Гав");<br> }
}

10. Полиморфизм и virtual/override

class Animal
{<br> public virtual void Sound()<br> {<br> Console.WriteLine("Звук животного");<br> }
}

class Dog : Animal
{<br> public override void Sound()<br> {<br> Console.WriteLine("Гав");<br> }
}

11. Абстрактные классы и интерфейсы

Абстрактный класс

abstract class Shape
{<br> public abstract double GetArea();<br>}

Интерфейс

interface IPrintable
{<br> void Print();<br>}

Реализация:

class Document : IPrintable
{<br> public void Print()<br> {<br> Console.WriteLine("Печать документа");<br> }
}

12. Коллекции

Подключение:

using System.Collections.Generic;

List<T>

List<int> numbers = new List<int> { 1, 2, 3 };
numbers.Add(4);
numbers.Remove(2);
Console.WriteLine(numbers[0]);
Console.WriteLine(numbers.Count);

Dictionary<TKey, TValue>

Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Иван"] = 20;
ages["Анна"] = 22;

Console.WriteLine(ages["Иван"]);

Проверка ключа:

if (ages.ContainsKey("Иван"))
{<br> Console.WriteLine("Есть такой ключ");<br>}

HashSet<T>

HashSet<int> set = new HashSet<int>();
set.Add(1);
set.Add(1); // дубль не добавится

Queue<T>

Queue<string> q = new Queue<string>();
q.Enqueue("A");
q.Enqueue("B");
Console.WriteLine(q.Dequeue()); // A

Stack<T>

Stack<int> st = new Stack<int>();
st.Push(10);
st.Push(20);
Console.WriteLine(st.Pop()); // 20

13. Лямбда-выражения

Лямбда — это короткая запись анонимной функции.

(int x) => x * x

Примеры:

Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // 25
Action<string> print = s => Console.WriteLine(s);
print("Привет");
Predicate<int> isEven = x => x % 2 == 0;
Console.WriteLine(isEven(4)); // True

14. LINQ и работа с коллекциями

Подключение:

using System.Linq;

Where

List<int> nums = new List<int> { 1, 2, 3, 4, 5 };
var even = nums.Where(x => x % 2 == 0);

Select

var squares = nums.Select(x => x * x);

First / FirstOrDefault

int first = nums.First();
int value = nums.FirstOrDefault(x => x > 10); // 0, если нет

OrderBy

var sorted = nums.OrderBy(x => x);
var desc = nums.OrderByDescending(x => x);

Any / All

bool hasEven = nums.Any(x => x % 2 == 0);
bool allPositive = nums.All(x => x > 0);

15. Исключения

try-catch

try
{<br> int x = int.Parse("abc");<br>}
catch (FormatException)
{<br> Console.WriteLine("Неверный формат");<br>}

Несколько catch

try
{<br> int[] arr = new int[2];<br> Console.WriteLine(arr[5]);<br>}
catch (IndexOutOfRangeException)
{<br> Console.WriteLine("Выход за границы массива");<br>}
catch (Exception ex)
{<br> Console.WriteLine(ex.Message);<br>}

finally

try
{<br> Console.WriteLine("Работа");<br>}
finally
{<br> Console.WriteLine("Блок finally выполнится всегда");<br>}

throw

if (age < 0)
throw new Exception("Возраст не может быть отрицательным");

16. Делегаты

Делегат — это тип, который хранит ссылку на метод.

Объявление делегата

delegate int Operation(int a, int b);

Использование

static int Add(int a, int b) => a + b;

Operation op = Add;
Console.WriteLine(op(2, 3));

17. Встроенные делегаты

Func

Возвращает значение.

Func<int, int, int> sum = (a, b) => a + b;

Action

Ничего не возвращает.

Action<string> show = s => Console.WriteLine(s);

Predicate

Возвращает bool.

Predicate<int> isPositive = x => x > 0;

18. События

Событие — это механизм уведомления о том, что что-то произошло.

class Button
{<br> public event Action Click;<br><br> public void OnClick()<br> {<br> Click?.Invoke();<br> }
}

Использование:

Button btn = new Button();
btn.Click += () => Console.WriteLine("Кнопка нажата");
btn.OnClick();

Ключевые моменты

  • event защищает делегат от внешнего вызова
  • += подписка
  • -= отписка
  • ?.Invoke() безопасный вызов события

19. Модификаторы доступа

  • public — доступен везде
  • private — только внутри класса
  • protected — внутри класса и наследников
  • internal — внутри сборки

Пример:

class Test
{<br> private int x;<br> public int y;<br>}

20. static

static означает, что член принадлежит классу, а не объекту.

class MathHelper
{<br> public static int Square(int x) => x * x;<br>}

Вызов:

int s = MathHelper.Square(5);

21. Полезные операторы и сокращения

Интерполяция строк

string name = "Олег";
Console.WriteLine($"Привет, {name}");

null-coalescing

string name = null;
string result = name ?? "Без имени";

null-conditional

person?.SayHello();