Шпаргалка по C#
Шпаргалка по C#
1. Базовый синтаксис
Структура программы
using System;
class Program
{
static void Main()
{
Console.WriteLine("Привет, мир!");
}
}
Переменные
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)
{
Console.WriteLine("Положительное");
}
else if (x < 0)
{
Console.WriteLine("Отрицательное");
}
else
{
Console.WriteLine("Ноль");
}
switch
switch (day)
{
case 1:
Console.WriteLine("Понедельник");
break;
case 2:
Console.WriteLine("Вторник");
break;
default:
Console.WriteLine("Неизвестно");
break;
}
Тернарный оператор
string result = x > 0 ? "Плюс" : "Не плюс";
3. Циклы
for
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
while
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
do while
int i = 0;
do
{
Console.WriteLine(i);
i++;
} while (i < 5);
foreach
int[] arr = { 1, 2, 3 };
foreach (int item in arr)
{
Console.WriteLine(item);
}
4. Массивы
int[] nums = { 10, 20, 30 };
Console.WriteLine(nums[0]);
nums[1] = 99;
Console.WriteLine(nums.Length);
Двумерный массив:
int[,] matrix = {
{1, 2},
{3, 4}
};
Console.WriteLine(matrix[0, 1]); // 2
5. Методы
static int Sum(int a, int b)
{
return a + b;
}
Вызов:
int result = Sum(3, 4);
Метод без возврата:
static void PrintHello()
{
Console.WriteLine("Hello");
}
Параметры по умолчанию:
static void Greet(string name = "Гость")
{
Console.WriteLine($"Привет, {name}");
}
6. Классы и объекты
Класс
class Person
{
public string Name;
public int Age;
public void SayHello()
{
Console.WriteLine($"Привет, я {Name}");
}
}
Создание объекта
Person p = new Person();
p.Name = "Анна";
p.Age = 18;
p.SayHello();
7. Свойства
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
С ограничением:
class Person
{
private int age;
public int Age
{
get { return age; }
set
{
if (value >= 0)
age = value;
}
}
}
8. Конструкторы
class Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
Person p = new Person("Иван", 20);
9. Наследование
class Animal
{
public void Eat()
{
Console.WriteLine("Ест");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Гав");
}
}
10. Полиморфизм и virtual/override
class Animal
{
public virtual void Sound()
{
Console.WriteLine("Звук животного");
}
}
class Dog : Animal
{
public override void Sound()
{
Console.WriteLine("Гав");
}
}
11. Абстрактные классы и интерфейсы
Абстрактный класс
abstract class Shape
{
public abstract double GetArea();
}
Интерфейс
interface IPrintable
{
void Print();
}
Реализация:
class Document : IPrintable
{
public void Print()
{
Console.WriteLine("Печать документа");
}
}
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("Иван"))
{
Console.WriteLine("Есть такой ключ");
}
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
{
int x = int.Parse("abc");
}
catch (FormatException)
{
Console.WriteLine("Неверный формат");
}
Несколько catch
try
{
int[] arr = new int[2];
Console.WriteLine(arr[5]);
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Выход за границы массива");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
try
{
Console.WriteLine("Работа");
}
finally
{
Console.WriteLine("Блок finally выполнится всегда");
}
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
{
public event Action Click;
public void OnClick()
{
Click?.Invoke();
}
}
Использование:
Button btn = new Button();
btn.Click += () => Console.WriteLine("Кнопка нажата");
btn.OnClick();
Ключевые моменты
eventзащищает делегат от внешнего вызова+=подписка-=отписка?.Invoke()безопасный вызов события
19. Модификаторы доступа
public— доступен вездеprivate— только внутри классаprotected— внутри класса и наследниковinternal— внутри сборки
Пример:
class Test
{
private int x;
public int y;
}
20. static
static означает, что член принадлежит классу, а не объекту.
class MathHelper
{
public static int Square(int x) => x * x;
}
Вызов:
int s = MathHelper.Square(5);
21. Полезные операторы и сокращения
Интерполяция строк
string name = "Олег";
Console.WriteLine($"Привет, {name}");
null-coalescing
string name = null;
string result = name ?? "Без имени";
null-conditional
person?.SayHello();