dir.by  
  Поиск  
Компьютер, программы
C# (programming language)
 What is a class? in the C#? 
посмотрели 12944 раз
обновлено: 28 November 2018
C# the program can be represented as interconnected objects.
Class in the C# describes an object.
Keyword class used to define a class
Example
  C#  
// describe the class
class Book
{
     // class members
     protected string Name;
     protected int Price;

     // class constructor without parameters
     public Book()
     {
     }

     // class constructor with parameters
     public Book(string name, int price)
     {
          Name = name;
          Price = price;
     }

     // class methods
     public void SetName(string name)
     {
          // assign the title of the book
          Name = name;
     }

     public void SetPrice(int price)
     {
          // assign the price of the book
          Price = price;
     }

     public void ShowInfo()
     {
          // show information about the book on the screen
          Console.WriteLine("Title of the book " + Name + ", price " + Price);
     }
}
Class fields (contain information)
Name
Data type
access modifier
protected string Name
Could choose any English name
string contains text
protected - this means that we can't use outside the class
protected int Price
Could choose any English name
int contains a number
protected means we can't use outside of the class
 
Class Constructors (initializing class fields when creating an object)
public Book()
The name of the constructor is always the same as the name of the class
() means that there are no parameters

Note! The class constructor has no return type
public means that we can call inside the class and outside the class (anywhere)
public Book(string name, int price)
The name of the class constructor is always the same as the name of the class
(string name, int price) means that 2 parameters:

1st parameter with data type string

2nd parameter with data type int

Note! The class constructor has no return type
public means that we can call inside the class and outside the class (anywhere)
 
Class Methods (class methods perform an action on data)
public void SetPrice(int price)
Could choose any English name
(int price) means that
1st parameter with data type int

Return type void means that the method does not return a result
public means that we can call inside the class and outside the class (anywhere)
public void ShowInfo()
Could choose any English name
() means that
the method has no parameters

Return type void means that the method does not return a result
public means that we can call inside the class and outside the class (anywhere)
Creating a Class Object
  C#  
Book book1 = new Book();
To create a class object Book you need to use an expression

new Book();

Operator new allocates memory for a class Book.
And then the default constructor is called, which takes no parameters.

After execution new memory will be allocated.
all data will be stored in this memory Book.
Variable book1 get a link to memory.
Full code
  C#     Creating a new console application C# and write:
using System;

namespace ConsoleApplication1
{
     // describe the class
     class Book
     {
          // class fields
          protected string Name;
          protected int Price;

          // class constructors
          public Book()
          {
          }

          public Book(string name, int price)
          {
               Name = name;
               Price = price;
          }

          // class methods
          public void SetName(string name)
          {
               // assign the title of the book
               Name = name;
          }

          public void SetPrice(int price)
          {
               // assign the price of the book
               Price = price;
          }

          public void ShowInfo()
          {
               // show information about the book on the screen
               Console.WriteLine("Title of the book " + Name + ", price " + Price);
          }
     }

     // main class of the program
     class Program
     {
          static void Main(string[] args)
          {
               // create a class object Book
               Book book1 = new Book(); // the class constructor is called Book()
               book1.SetName("Harry Potter"); // call the method SetName
               book1.SetPrice(20); // call the method SetPrice
               book1.ShowInfo(); // call the method ShowInfo
               // on the screen we will see "Title of the book Harry Potter, price 20"

               // create a class object Book
               Book book2 = new Book("The Three Musketeers", 30); // the class constructor is called Book(string, int)
               book2.ShowInfo(); // call the method ShowInfo
               // on the screen we will see "Title of the book The Three Musketeers, price 30"
          }
     }
}
in the C# classes can contain
• class fields (above described with an example)
• class methods (above described with an example)
Constants
properties
class constructors
class destructors
Events
Operators
Indexers
nested types
Delegates
Access modifiers for methods, properties, fields for a class in the C#
Fields, methods, properties in the class have access modifiers.
Access modifiers allow you to set the scope.
Scope is the area in which you can use a given variable or method.
public
Public Class Member.
this class member is accessible from anywhere in the code
This class member is available for other assemblies.

Example 1 no compilation errors
  C#  
class Book
{
     // class field
     public string Name;

     // class method
     public string GetInfo()
     {
          return "Title of the book " + Name; // get the value from the class field
     }
}

class Program
{
     static void Main(string[] args)
     {
          // create a class object
          Book book1 = new Book();

          // set a value for the class object
          book1.Name = "aaa";

          // call the method GetInfo
          string str1 = book1.GetInfo();
     }
}


Example 2 (inheritance) no compilation errors
  C#  
class Book
{
     // class field
     public string Name;

     // class method
     public string GetInfo()
     {
          return "Title of the book " + Name; // get the value from the class field
     }
}

class ShowBook : Book
{
     public void Show()
     {
          string info = GetInfo(); // call the method GetInfo from the base class Book
          Console.WriteLine(info);
     }
}

class Program
{
     static void Main(string[] args)
     {
          ShowBook book2 = new ShowBook();

          // set a value for the class object
          book2.Name = "aaa";

          // call the method GetInfo
          string str2 = book2.GetInfo();

          // call the method Show
          book2.Show();
     }
}

protected
Such a class member is available in the current class and in derived classes.
Derived classes can reside in other assemblies.
Such a class member is NOT AVAILABLE for a class object.

Example 1 (2 compile-time errors)
  C#  
class Book
{
     // class field
     protected string Name;

     // class method
     protected string GetInfo()
     {
          return "Title of the book " + Name; // get the value from the class field
     }
}

class Program
{
     static void Main(string[] args)
     {
          // create a class object
          Book book1 = new Book();

          // set a value for the class object
          book1.Name = "aaa"; // Compilation error! Book.Name is inaccessible due to its protection level

          // call the method GetInfo
          string str1 = book1.GetInfo(); // Compilation error! Book.GetInfo() is inaccessible due to its protection level
     }
}


Example 2 (inheritance) 3 compile-time errors
  C#  
class Book
{
     // class field
     protected string Name;

     // class method
     protected string GetInfo()
     {
          return "Title of the book " + Name; // get the value from the class field
     }
}

class ShowBook : Book
{
     protected void Show()
     {
          string info = GetInfo(); // call the method GetInfo from the base class Book
          Console.WriteLine(info);
     }
}

class Program
{
     static void Main(string[] args)
     {
          ShowBook book2 = new ShowBook();

          // set a value for the class object
          book2.Name = "aaa"; // Compilation error! Book.Name is inaccessible due to its protection level

          // call the method GetInfo
          string str2 = book2.GetInfo(); // Compilation error! Book.GetInfo() is inaccessible due to its protection level

          // call the method Show
          book2.Show(); // Compilation error! ShowBook.Show() is inaccessible due to its protection level
     }
}
private
Private class member.
Only available in the same class.
Such a class member is NOT AVAILABLE for a class object.
Such a class member is NOT AVAILABLE for methods of the inherited class.

Example 1 (2 compile-time errors)
  C#  
class Book
{
     // class field
     private string Name;

     // class method
     private string GetInfo()
     {
          return "Title of the book " + Name; // get the value from the class field
     }
}

class Program
{
     static void Main(string[] args)
     {
          // create a class object
          Book book1 = new Book();

          // set a value for the class object
          book1.Name = "aaa"; // Compilation error! Book.Name is inaccessible due to its protection level

          // call the method GetInfo
          string str1 = book1.GetInfo(); // Compilation error! Book.GetInfo() is inaccessible due to its protection level
     }
}


Example 2 (inheritance) 4 compile-time errors
  C#  
class Book
{
     // class field
     private string Name;

     // class method
     private string GetInfo()
     {
          return "Title of the book " + Name; // get the value from the class field
     }
}

class ShowBook : Book
{
     private void Show()
     {
          string info = GetInfo(); // Compilation error! Book.GetInfo() is inaccessible due to its protection level
          Console.WriteLine(info);
     }
}

class Program
{
     static void Main(string[] args)
     {
          ShowBook book2 = new ShowBook();

          // set a value for the class object
          book2.Name = "aaa"; // Compilation error! Book.Name is inaccessible due to its protection level

          // call the method GetInfo
          string str2 = book2.GetInfo(); // Compilation error! Book.GetInfo() is inaccessible due to its protection level

          // call the method Show
          book2.Show(); // Compilation error! ShowBook.Show() is inaccessible due to its protection level
     }
}
internal
Same as public
but not available for other builds.

Example 1 (no compilation errors)
  C#  
class Book
{
     // class field
     internal string Name;

     // class method
     internal string GetInfo()
     {
          return "Title of the book " + Name; // get the value from the class field
     }
}

class Program
{
     static void Main(string[] args)
     {
          // create a class object
          Book book1 = new Book();

          // set a value for the class object
          book1.Name = "aaa";

          // call the method GetInfo
          string str1 = book1.GetInfo();
     }
}


Example 2 (inheritance) no compilation errors
  C#  
class Book
{
     // class field
     internal string Name;

     // class method
     internal string GetInfo()
     {
          return "Title of the book " + Name; // get the value from the class field
     }
}

class ShowBook : Book
{
     internal void Show()
     {
          string info = GetInfo(); // call the method GetInfo from the base class Book
          Console.WriteLine(info);
     }
}

class Program
{
     static void Main(string[] args)
     {
          ShowBook book2 = new ShowBook();

          // set a value for the class object
          book2.Name = "aaa";

          // call the method GetInfo
          string str2 = book2.GetInfo();

          // call the method Show u class ShowBook
          book2.Show();
     }
}

protected internal
Combines the functionality of two modifiers.
Same as protected
but not available for other builds.

  C#     Example
class Book
{
     protected internal string Name;
     ...
}
private protected
Combines the functionality of two modifiers.
Same as private
but not available for other builds.

  C#     Example
class Book
{
     private protected string Name;
     ...
}
If you don't have an access modifier, default will be set private.

  C#     Example
class Book
{
     string Name; // private
     ...
}
Class Access Modifiers in the C#
Classes have access modifiers.
Access modifiers allow you to set the scope.
public
A public class. This class is available from anywhere in the code, as well as from other programs and builds.

  C#     Example
public class Book
{
     ...
}
internal
The class is accessible from anywhere in the code in the same assembly, but it is not available to other programs and assemblies.

  C#     Example

internal class Book
{
     ...
}
If there is no access modifier for the class, default will be set internal.

  C#     Example

class Book // internal
{
     ...
}
 
← Previous topic
Exception handling in C#. Operator try catch finally
 
Next topic →
Class Access Modifiers in the C#. Access modifiers for methods, properties, fields in the C#
 
Your feedback ... 1 Comments
НЛО
11 Augusta 2021 11:08
  C#  

class Program
{
      static void Main(string[] args)
      {
            Book book = new Book();
            book.SetName("Elon Mask");
            book.SetPrice(300);
            book.Info();
      }

}
class Book
{
      protected string Name;
      protected int Price;
      public Book()
      {

      }
      public Book(string name, int price)
      {
            Name = name;
            Price = price;
      }
      public void SetName(string name)
      {
            Name = name;
      }
      public void SetPrice(int price)
      {
            Price = price;
      }
      public void Info()
      {
            Console.WriteLine("Name is book: " + Name + "Price is Book: " + Price + "$");
      }
}
   
Your Name
Your comment (www links can only be added by a logged-in user)

Экскурсии по Москве Экскурсии по Москве: пешеходные, автобусные и речные прогулки на любой вкус
  Объявления  
  Объявления  
 
Download and install Microsoft Visual Studio
Download and install Visual Studio 2026 (for learning C#, writing programs): WPF, ASP.NET, ASP.NET Core, UWP, Maui, Xamarin, Unity, MonoGame)
Download and install Visual Studio 2022 (for learning C#, writing programs): WPF, ASP.NET, ASP.NET Core, UWP, Maui, Xamarin, Unity, MonoGame)
Скачать и установить Visual Studio 2019 (для изучения C#, написание программ: WPF, ASP.NET, ASP.NET Core, Xamarin, Unity, MonoGame)
Download and install Visual Studio 2017 (для изучения C#, написание программ: WPF, ASP.NET, ASP.NET Core, Xamarin, Unity, MonoGame)
Новое приложение для изучения C#
Creating a new console application to learn C#
Debugging Code
Debug.Assert(false) Debugging Code in C#
For debugging, option "Common Language Runtime Exceptions" see exceptions when a program is running C#
Атрибут [Obsolete("My method is outdated. Do not use", false)] Warning when compiling code in the C#
Data Types C#
C# data types: number (bool, char, byte, int, long, float, double, decimal), text (string), enumeration (enum), class (class), structure (struct)
Structure Boolean in the C# it is a flag with values true or false (bool) and methods for conversion bool
Structure Int32 in the C# it is a signed integer (int) and methods for conversion int
Structure Single in the C# this is a floating-point number (float) and methods for conversion float
var ... Variable of any type in the C#. Example: var str = "Hello!";
Type dynamic in the C#
Default values in the C#
Storing objects in memory. Removing Objects from Memory
Reference types and value types in the C#
Stack (stack) - memory for method parameters and local variables in the C#
Heap - dynamic memory available at run time in the C#
Interface IDisposable. Write code to properly release unmanaged resources in the destructor and in the interface IDisposable in the C#
Memory. Garbage collector (garbage collector). Automatic memory freeing in the C#
C# type conversion
C# converting a string to a number (string → short, int, long, ushort, uint, ulong, float, double, decimal) | Use Culture (system settings)
C# converting a number to a string (int, double, short, ... → string) with the required accuracy
Text in C# (type string and class String)
Алгоритм пересечения прямоугольников
What is text in the C# ? Type string and class String. Methods for working with text.
Length (string length in C#). Example: string str1 = "Hello"; int v1 = str1.Length;
CompareTo (compares case-sensitive text in C#). Example: bool bIsSame = str1.CompareTo(str2)==0;
ToLower (converts text to lowercase in C#). Example: string str1 = "HELLO World!"; string str2 = str1.ToLower();
ToUpper (converts text to uppercase in C#). Example: string str1 = "Hello World!"; string str2 = str1.ToUpper();
Split (split the string into words in C#). Example: string[] arrWords = strText.Split(' ');
StartsWith (checks the beginning of the text with the specified case-sensitive text in C#). Example: bool bStart = str1.StartsWith(str2);
Contains (checks whether the text specified is case-sensitive or not in case-sensitive C#). Example: bool bFound = str1.Contains(str2);
IndexOf (searches for a case-sensitive string and returns the position in C#). Example: int pos = str1.IndexOf(str2);
Substring (returns part of the text from the specified position and length in the C#). Example: string str1 = "Hello World!"; string str2 = str1.Substring(2, 5);
IsNullOrEmpty (checks the text for blank or for null in the C#). Example: string name = "Hello World!"; bool bFlag = String.IsNullOrEmpty(name);
IsNullOrWhiteSpace (validates text on null or on text with spaces in the C#). Example: string name = "   "; bool bFlag = String.IsNullOrWhiteSpace(name);
[] (returns a character from the specified position in the C#). Example: char symbol = str[1];
Format (text formatting, strings in the C#). Example: string strNew = String.Format("Hello {0}, {1}", name, year);
+ (add lines and text in the C#). Example: string str = str1 + str2 + " people!";
$ (string interpolation in the C#). Example: string result = $"Hello {a} + {b} = {a + b}";
Symbol @ before the beginning of the line in the C#. Example: string str1 = @"aaa";
Используем вместе @ и $ (интерполяцию строк в C#)
DateTime (дата и время) в C#
What is DateTime in C# ? Convert to a string with the format
Enumerations in C # (enum)
What is enumeration? (enum) in the C# ?
How to convert text to enum in C#
How to enumerate all elements in enum in C#
null
null value for simple types. Use ? or Nullable in the C#
Operator ?? (null-union) in the C#
try-catch
Exception handling in C#. Operator try catch finally
Classes in C# (class)
What is a class? in the C#?
Class Access Modifiers in the C#. Access modifiers for methods, properties, fields in the C#
'partial class' in the C#. Description of the class in different files
Constructors for a class
Class Constructor in the C#
Initializing a Class Object (set values for fields) in the C#
To call the constructor at the base class in the C#
Static constructor in class C#
'base' To call a method from the base class. To call a variable from the base class. To call the constructor from the base class. C#
'this' To set or get a value from a class field. To call the constructor from the class. C#
Class Destructors
Class Destructor in the C#
Destructors in classrooms (how basic destructors are called) C#
Inheritance
What is class inheritance in C# ?
Inheritance using new
Use new for the interface method. Inheriting an interface from an interface with the same method
Use new for the class method. Inheriting a class from a class in C#.
Inheritance using sealed
sealed class. Prohibition to inherit in the C#
Inheriting a class from a class in C#. We use words virtual, override, sealed for class methods
Abstract class
What is an abstract class? in the C# ? Abstract methods, properties, indexes.
Inheritance from a class abstract in the C#. Use abstract and override for class methods
Constants and readonly fields in the classroom
Constants in the classroom C#
readonly . For a class field. This field is read-only in C#
Properties get and set in the classroom C# (accessors)
get set Properties in a class C#
Наследование (virtual, override) для аксессоров get и set в C#
Операторы, индексаторы в C#
Операторы в классе C#. Перегрузка операторов: > < ++ + true false
Индексаторы в классе C#
Вложенные типы в C#
Вложенный класс, структура в C#
Параметры в методе класса C#
ref и out (возврат параметров по ссылке в методе) C#. Пример: public void AddValue(ref int value)
Параметры по умолчанию (необязательные параметры) в методе C#. Пример: public int CalculateSum(int a, int b, int c=7)
Именованные параметры C#. Пример: public void CalculateSum(a:7, b:3);
Универсальные методы, универсальные классы в C# (шаблоны)
Метод с универсальными параметрами в C# (шаблоны). Пример: public double Sum<T1, T2>(T1 value1, T2 value2) { ... }
Обобщенный (типизированный) класс в C# (шаблоны). Пример class Book<T> { ... }
where Ограничение типа в обобщенном (типизированном) классе в C# (шаблоны). Пример class Dog<T> where T : Cat
Преобразование объекта класса из одного типа в другой
explicit это явный оператор преобразования в классе C#
implicit это неявный оператор преобразования в классе C#
Преобразование объекта класса из одного типа в другой в C#. Используем try ( ) is as
Преобразование объекта класса из одного типа в другой в C#. Используем pattern matching is switch
Объект класса в C#
? оператор условного null в C#
Объект класса содержит ссылку в C#
Как чтобы при копировании объектов в C# копировались данные класса, а не ссылка?
Статический конструктор и статические свойства и методы
Статический конструктор в классе C#
Статические методы, свойства, члены в классе C#
Дополнительные возможности класса в C#
Метод расширения в C# (this в первом параметре метода). Пример: static public void AddValues(this List<int> myList, int value1, int value2)
Правила именования классов в C#
Какими буквами строчными или заглавными называть классы, методы, свойства ... в C#
Правильно ли для каждого класса в C# создавать свой .cs файл? Или писать классы C# в одном .cs файле?
Статический класс
Статический класс в C#
Анонимный класс
Объект с анонимным (отсутствующим) типом в C#. Пример: var book = new { BookName = "Властелин Колец", Price = 100 };
Interfaces
Что такое interface в C# ?
Наследование interface от interface в C#
Наследование класса от класса от interface в C#. Используем override и virtual для методов класса
Обобщенный (типизированный) интерфейс в C# (шаблоны). Пример interface IUser<T> { ... }
Структура struct
Что такое структура в C#?
Модификаторы доступа структуры в C#. Модификаторы доступа для методов, свойств, полей структуры в C#
Инициализация объекта структуры (установка значений для полей) в C#
Как поменять значение в массиве структур или в коллекции структур (List) в C#
Вложенная структура в C#
Преобразование объекта структуры из одного типа в другой
implicit это неявный оператор преобразования структуры в C#
explicit это явный оператор преобразования структуры в C#
Отложенная загрузка class Lazy в C#
Отложенное создание объекта в памяти (class Lazy в C#)
Кортежи (tuple)
Кортежи (tuple) в C#
Динамические объекты с любыми свойствами
DynamicObject и ExpandoObject в C#
Массивы
Что такое массивы? array в C#
Инициализация массива (заполнение элементов массива array) в C#
params передача любого количества параметров в метод в C#
Класс Array (для работы с массивом) C#
Коллекции
Что такое коллекции в C# ?
Что такое необобщенные коллекции в C# ? Классы ArrayList, Stack, Queue, Hashtable, SortedList, BitArray
Что такое обобщенные (типизированные) коллекции в C# ? Классы List<T>, SortedList<T>, Stack<T>, Dictionary<TKey,TValue>, LinkedList<T>, Queue<T>, HashSet<T>, SortedSet<T>, ConcurrentDictionary<TKey, TValue>, SortedDictionary<TKey, TValue>
Классы необобщенных коллекций (в одной коллекции хранятся элементы разного типа)
Интерфейс IEnumerable. Самый базовый интерфейс для коллекций в C#
Интерфейсы: ICollection, IList, IDictionary. Основа для коллекций в C#
Класс ArrayList (коллекция в C#)
Что такое ArrayList в C# ?
Класс SortedList (коллекция в C#)
Что такое SortedList в C# ?
Класс Stack (коллекция в C#)
Что такое Stack в C# ?
Класс Queue (коллекция в C#)
Что такое Queue в C# ?
Класс Hashtable (коллекция в C#)
Что такое Hashtable в C# ?
Класс BitArray (коллекция в C#)
Что такое BitArray в C# ?
Классы обобщенных, типизированных коллекций в C# (в одной коллекции хранятся элементы одного типа)
Интерфейс IEnumerable<T>. Самый базовый интерфейс для типизированных коллекций в C#
Интерфейсы: ICollection<T>, IList<T>, ISet<T>, IDictionary<TKey, TValue>. Основа для типизированных коллекций в C#
Класс List<T> (типизированная коллекция в C#)
Что такое List<T> в C# ?
Initializing the Collection List in curly brackets in the C#
for, foreach (проходим все элементы в List<T>) в C#
Find (ищем элемент по критерию в List<T>) в C#
FindAll (ищем список элементов по критерию в List<T>) в C#
ForEach (для каждого элемента List<T> выполняется действие) в C#
Класс LinkedList<T> (типизированная коллекция в C#)
Что такое LinkedList<T> в C# ?
Класс SortedList<TKey, TValue> (типизированная коллекция в C#)
Что такое SortedList<TKey, TValue> в C# ?
Класс Stack<T> (типизированная коллекция в C#)
Что такое Stack<T> в C# ?
Класс Queue<T> (типизированная коллекция в C#)
Что такое Queue<T> в C# ?
Класс HashSet<T> (типизированная коллекция в C#)
Что такое HashSet<T> в C# ?
Как устроен HashSet<T> в C#
Класс SortedSet<T> (типизированная коллекция в C#)
Что такое SortedSet<T> в C# ?
Класс ObservableCollection<T> (типизированная коллекция в C#)
Что такое ObservableCollection<T> в C# ?
Класс Dictionary<TKey, TValue> (типизированная коллекция в C#)
Что такое Dictionary<TKey, TValue> в C# ?
Инициализация элементов в конструкторе Dictionary<TKey, TValue> в C#
Как устроен Dictionary<TKey, TValue> в C#
Как в C# сконвертировать IEnumerable в → Dictionary<TKey, TValue> . Используем метод ToDictionary
Класс SortedDictionary<TKey, TValue> (типизированная коллекция в C#)
Что такое SortedDictionary<TKey, TValue> в C# ?
Класс ConcurrentDictionary<TKey, TValue> (типизированная коллекция в C#)
Что такое ConcurrentDictionary<TKey, TValue> в C# ?
AddOrUpdate (добавить или обновить значение по ключу в ConcurrentDictionary<TKey, TValue>) в C#
Асимптотическая сложность для добавления, удаления, взятия элемента в коллекциях
Asymptotic complexity for adding, removing, taking an element in collections C# (List, SortedList, Stack, Dictionary, LinkedList, Queue, HashSet, SortedSet, ConcurrentDictionary, SortedDictionary)
Сортировка элементов в массиве [] и коллекции List
Сортировка элементов в массиве [] и коллекции List<T> в C#. Интерфейс IComparable
Сортировка элементов в массиве [] и коллекции List<T> в C#. Интерфейс IComparer
Моя реализация IEnumerator, IEnumerable и итераторы
Пример: Моя реализация интерфейсов IEnumerable и IEnumerator в C#
Итераторы и yield в C#. Примеры реализации IEnumerable с помощью yield
Методы расширения для IEnumerable (поиск, замена, выборка значений) в C#
Методы поиска, замены, выборки значений в IEnumerable<T>. Методы расширений для IEnumerable<T> в C#
Any (метод расширения IEnumerable<T>) в C#
Select (метод расширения IEnumerable<T>) в C#
GroupBy (extension method IEnumerable<T>) in the C#
GroupJoin (extension method IEnumerable<T>) in the C#
Сортировка, фильтрация в LINQ (Language-Integrated Query)
Что такое LINQ в C# ?
Сортировка, фильтрация элементов списка с помощью LINQ в C#
Книги для изучения LINQ в C#
Указатели
Указатели в C#. Оператор unsafe
Указатели на структуры, поля классов, массивы в C# . Операторы unsafe, stackalloc, fixed
Работа с файлами
Открываем файл, читаем текст из файла и разбиваем по словам. C#
Создаем текстовый файл, пишем текст в файл C#
Создаем HTML файл, пишем табличные данные в HTML файл | C#
Создаем бинарный файл, пишем байты в файл C#
Частичная загрузка файла с FTP в C#
Class Path. Combine method - merges the strings into the full path of the file. And other methods of the Path class | C#
Сериализация
Что такое сериализация объекта в C# ? Атрибут [Serializable]
Сериализация C# объекта в бинарный файл. Класс BinaryFormatter. Атрибут [Serializable]
Сериализация C# объекта в XML файл. Класс XmlSerializer. Атрибут [Serializable]
Сериализация C# объекта в JSON файл. Класс DataContractJsonSerializer. Атрибут [Serializable]
Сериализация C# объекта в SOAP файл. Класс SoapFormatter. Атрибут [Serializable]
Пространства имен
Пространства имен namespace using в C#
Delegate
Делегат (delegate) в C#
Добавление метода(методов) в делегате C#. Объединение делегатов. Удаление метода из делегата
Делегат как параметр в методе C#
Безымянный, анонимный метод в C# (метод описанный на месте параметра, делегата)
Универсальные делегаты
Универсальные, обобщенные делегаты в C# (шаблоны)
Универсальные делегаты Action, Predicate и Func в C#
События
События (event) в C#
Лямда
Лямда (пример) в C#
Регулярные выражения
Регулярные выражения в C#
Разбиваем текст на слова (регулярные выражения в c#)
Ставим * вместо фамилии после первой буквы (регулярные выражения в c#)
Разбиваем текст на слова (регулярные выражения в c#)
Процесс, модули процесса
Процесс в C# (класс Process)
Модули процесса в С# (класс ProcessModule)
Потоки, многопоточность
Потоки в C# (класс Thread)
Пул потоков в C# (Thread Pool)
В чем отличие background (фоновый поток) и foreground (на переднем плане поток) в C# ?
Синхронизация потоков в C#
Parallel Library Task (TPL) Параллельное программирование задач
Parallel Library Task (TPL). Библиотека параллельных задач в C#
Класс Parallel используя метод Invoke параллельно выполненяет методы, циклов for и foreach (на разных ядрах процессора) в C#
PLINQ распараллеливает LINQ запросы для выполнения на разных ядрах процессора в C#
Асинхронные методы (async и await)
class Task в C#
Асинхронное программирование в C# (async, await как оформлять)
Асинхронное программирование в C# (используем async, await и Task на примере)
Асинхронное программирование в C# (теория)
Домены приложений
Что такое Домены приложений в C# ? (класс AppDomain)
Пример "Информация о домене приложения" (имя текущего домена, перечисляем сборки) в C#
Пример "Создаем 2-ой домен приложения. Пишем класс в 1-ом домене и используем во 2-ом домене. MarshalByRefObject в C#
Пример "Загружаем 2-ой домен приложения из файла, запускаем вычисления, выгружаем 2-ой домен из памяти" в C#
Атрибуты
Атрибуты для класса, метода, свойства в C#
Атрибут [Conditional("AAA")] . Для компиляции игнорировать метод или свойство если не определен символ условной компиляции в C#
Attribute [Obsolete("My method is outdated. Do not use", false)] Warning when compiling code in the C#
Атрибут [Display(Name = "Sleep at night")] . Для хранения какого нибудь текста прикрепленного к переменной | C#
Аттрибут [Required(ErrorMessage = "Пожалуйста, введите название")] описывается для свойства в C# классе и требует чтобы свойство было заполнено, если не заполнено на экране ошибка ErrorMessage в ASP.NET MVC
Аттрибут [Remote("IsValidAuthor", "Home", ErrorMessage = "Enter correct author of book")] описывается для свойства в C# классе и проверяет это свойство на правильность на сервере через метод IsValidAuthor в conroller Home, если метод возвращает false, то на экране будет ошибка ErrorMessage в ASP.NET MVC
Рефлексия (отражение) reflection в C#
Оператор nameof в C# (имя класса, имя метода, имя переменной)
Что такое рефлексия (отражение) в C# ? Класс Type
Создание объекта класса и вызов конструтора с параметрами используя рефлексию (отражение) reflection в C#
Как получить информацию атрибута для метода у класса. Используем reflection (отражение)
Как получить информацию атрибута для свойства у класса. Используем reflection (отражение)
Директивы препроцессора (if при компиляции)
Директивы препроцессора #define #undef #if #elif #else #endif в C#
Как определить #define для всех файлов (для всего проекта) в С# ?
Что такое сборка и исполняющая среда CLR ?
Assembly (Assembly) in C#. Compilation. Intermediate code IL (Intermediate Language). Metadata.
Как подключить C# сборку в проект?
Утилита ildasm.exe. Конвертирует сборку (C# exe, dll файл) в промежуточный язык IL (Intermediate Language). Эта утилита удобна для изучения
The runtime CLR (Common Language Runtime) in C# . JIT (Just-In-Time) compiler.
Создание и подключение нашей сборки
Создание нашей C# сборки (обычная сборка)
Подключение нашей C# сборки (обычная сборка)
Создание нашей C# сборки (разделяемая сборка)
Подключение нашей C# сборки (разделяемая сборка)
База данных в консольном приложении C#
Entity Framework в консольном приложении C#. Используем Code First (пишем c# код, а таблицы в базе данных создаются сами)
Read the image from the database and save it to a file | ADO.NET, C#, console application
Внедрение зависимостей (Dependency Injection) DI в C#
Dependency Injection (DI) Внедрение зависимостей в C#
Ninject (IoC-контейнер) управление зависимостями в C#
Autofac (IoC-контейнер) управление зависимостями в C#
Удобные утилиты Visual Studio
Графическая диаграмма классов в C# (View Class Diagram)
exe to C# code
"dotPeek" application for decompile (disassemble) exe to c# source code
В приложении C# вызываем C++ функции
What are managed code (managed code) and unmanaged code (unmanaged code)? | C# and C++
Marshaling (marshalling) in C#. Type Conversion Between Managed Code (managed code) and Unmanaged Code (unmanaged code)
In the application C# we call functions from Windows dll (C++ WinAPI). Attribute [DllImport("user32.dll")]
В приложении C# вызываем функции из моей dll (C++). Атрибут [DllImport("My.dll", CallingConvention = CallingConvention.Cdecl)]
Дополнительные темы, вопросы
Не создается новый проект в Visual Studio 2019. Ошибка "Object reference not set to instance of an object"
Ошибка компиляции C#: error CS1106: Extension method must be defined in a non-generic static class
Ошибка компиляции C#: error CS0246: The type or namespace name 'Point' could not be found (are you missing a using directive or an assembly reference?)
Почему метод Dictionary.TryGetValue не может найти значение по ключу в C# ?
Объектно-ориентированное программирование (ООП). Принципы ООП: абстрагирование, инкапсуляция, наследование, полиморфизм
Какими буквами в C# (заглавными или строчными или прописными) называть поля, методы в классе, интерфейсы, делегаты, параметры ?
Правильно ли для каждого класса в C# создавать свой .cs файл? Или писать классы C# в одном .cs файле?
Что лучше использовать встроенный тип int или класс Integer (тип string или класс String) на C#?
Как скачать и установить нужную .NET Framework версию в Visual Studio ?
Упаковка и распаковка значимых типов в C# (boxing/unboxing)
Error CS8107 Feature 'default literal' is not available in C# 7.0. Please use language version 7.1 or greater
Error "unable to connect to web server "iis express" | C# | Visual Studio 2017
Удаляем и устанавливаем NuGet в Visual Studio
При открытии проекта в Visual Studio 2019 ошибка: "project requires 'SQL Server 2012 Express LocalDB' which is not installed on this computer"
Математические операторы checked и unchecked
Математический оператор unchecked в C#
Математический оператор checked в C#
Дополнительный C# классы
C# класс Random
C# структура Point
C# структура PointF
C# структура Size
C# структура SizeF
C# структура Rectangle
C# структура RectangleF
Время
Время, истекшее с момента загрузки системы (в миллисекундах). System.Environment.TickCount в C#
Шифрование / Cryptography
Зашифруем пароль и проверим | C# console application
Excell
Чтение excel файла на C# (сonsole application)
WWW сайты для изучения C#
Сайты для изучения C#

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика