Learning C #. Third bucket

    Feedback Results


    About the audience


    Since there were a lot of comments about this, I decided to make the last attempt. I hope for feedback in the comments - it turned out “For Everyone” or not.

    About books


    After reading the comments, I decided to publish a list of books that were recommended there:
    C # 2008. Crash course
    CLR via C #
    C # and the .NET C # 2.0 platform
    . Complete guide

    About miscellaneous


    There were questions about the Mono speed. the other day I found a link to which there is a small test. geekswithblogs.net
    Testing was conducted on earlier versions, but I think the situation has not changed globally. IMHO

    Well, now let's continue the training ...

    Complex types


    C # allows you to define your own complex types based on the available simple types. Like primitives, complex types can be divided into types by reference and by value.

    Types by Value


    Structures


    In C #, a structure is a special type of class. Since a structure is placed on the stack, it can be created and copied more efficiently than a class. Consider a small structure:
    1. public struct Subscriber
    2. {
    3.  public long SubID;
    4.  public string FirstName;
    5.  public string LastName;
    6.  public string MiddleName;
    7.  public decimal Balance;
    8. }

    If we need to copy from one structure to another, then just put an equal sign. Let's create one Subscriber object, Sub1, and set the field values. After that, copy the value of all fields from one structure to another, Sub2:
    1. Subscriber Sub1;
    2. Subscriber Sub2;
    3. //Инициализируем структуру и заполним поля
    4. Sub1 = new Subscriber();
    5. Sub1.FirstName = "Вася";
    6. Sub1.LastName = "Пупкин";
    7. Sub1.MiddleName = "Какой-то";
    8. Sub1.Balance = 100;
    9.  
    10. //И теперь одной строкой копируем содержимое одной структуры в другую
    11. Sub2 = Sub1;

    Notice that we used new , although the structure is a type by value? Just access to the structure is possible before calling the operand new .
    In addition to copying, the structure makes function calls more accurate.

    If you are a C or C ++ guru, then be careful - they have changed! In C / C ++, the only difference between class and structure was that they were public, not private.
    The structure in C # is a completely new toy, not only by the fact that their members are private by default, but instances of structures and instances of classes are located in different places in memory.
    Structures can support most of the functions of a class (although it does not support inheritance of implementations), but they must be used carefully. Structures are best suited to provide small objects.

    Transfers


    Enumerations are integer types that the user defines. When you declare enumerations, you specify a set of valid values ​​that can be accepted by enumeration instances. In addition, you need to assign values ​​to intuitive names.
    In further work, transfers can play a very important role and make life easier for the programmer. The listings are declared like this:
    1. public enum DaysOfWeek
    2. {
    3.  Monday = 0,
    4.  Tuesday = 1,
    5.  Wednesday = 2,
    6.  Thursday = 3,
    7.  Friday = 4,
    8.  Saturday = 5,
    9.  Sunday = 6
    10. }

    Here we use integer values ​​that correspond to the days of the week. Access to a specific day of the week can be obtained like this: DaysOfWeek.Wednesday returns 2. Usually, transfers are used in cases where you need to pass the corresponding value to the method, which will go through all the values ​​using switch and give the corresponding result. We will talk more about switch in a bit later, but for now let's see an example:
    1. class Program
    2.   {
    3.     static void Main(string[] args)
    4.     {
    5.       WriteText(DaysOfWeek.Sunday);
    6.       Console.ReadLine();
    7.     }
    8.  
    9.     static void WriteText(DaysOfWeek days)
    10.     {
    11.       switch (days)
    12.       {
    13.         case DaysOfWeek.Monday:
    14.           Console.WriteLine("Понедельник - день тяжелый!");
    15.           break;
    16.         case DaysOfWeek.Tuesday:
    17.           Console.WriteLine("Вторник - это значит что понедельник уже прошел!");
    18.           break;
    19.         case DaysOfWeek.Wednesday:
    20.           Console.WriteLine("Среда! Средина недели!");
    21.           break;
    22.         //И так далее...
    23.       }
    24.     }
    25.   }


    Types by reference


    Classes


    Classes are the main user-defined type in C # and the .NET platform. Almost all programs have at least one class (theoretically, you can use a structure instead of a class) that contains the Main () method - the entry point to the program.
    Classes are composite data types that include data members and functions. classes also contain nested data types. We’ll talk more about classes through one “bucket”. =)

    Interfaces


    An interface in C # contains only abstract elements that have no implementation. The actual implementation of these elements must be contained in a class that is derived from this interface.
    C # interfaces can contain methods, properties, and indexers, but unlike, for example, Java, they cannot contain constant values.
    For example, if the interface contains a method, then it will work, but the code for implementing the method itself will not be inside it.

    Delegates


    Delegates are types that reference methods. They are similar to function pointers in C ++, but they allow you to instantiate a class and call both static methods and methods of a specific instance of the class.
    For beginners, it’s too early to delve into the intricacies, so just remember the name - we will return to them.

    Arrays


    An array defines how data is organized. An array is an ordered collection of elements of the same type. Each element of the array has indexes that determine the order of the elements. The number of indices characterizes the dimension of the array.
    In C #, as in many other languages, indices are specified by an integer type.
    In C #, a significant limitation of the C ++ language on the static nature of arrays has been removed. Arrays in C # are true dynamic arrays.

    Declaring Arrays

    Consider how one-dimensional arrays are declared.

    Declaration of one-dimensional arrays

    General declaration structure:
    [<attributes>] [<modifiers>] <type> <name>;

    Forget about attributes and modifiers for now. The declaration of a one-dimensional array is as follows:
    <type> [] <name>;

    Note, unlike in C ++, the square brackets are assigned not to the variable name, but to the type. They are an integral part of the definition of a class, so the notation T [] should be understood as a class, a one-dimensional array with elements of type T.
    1. //объявление массива
    2. int[] Integers;

    This is an example of an array declaration. You can also initialize the array using new :
    1. //Создаём массив из 32 значений типа int
    2. int[] Integers = new int[32];

    To access an array element, the usual syntax is:
    1. Integers[0] = 24;

    C # allows us to create arrays without initializing them, so they can change size during program execution.
    1. int[] Integers;
    2. Integers = new int[32];

    Arrays in C # retained the ability, as in C / C ++, to initialize the values ​​listed in curly braces.
    1. string[] Privet = {"раз", "два", "три"};
    2. //Что эквивалентно
    3. string[] Privet = new string[] {"раз", "два", "три"};

    However, there are pitfalls! For example, to set the size of an array, you cannot use a variable:
    1. int len = 3;
    2. //Не скомпилируется
    3. string[] Privet = new string[len] {"раз", "два", "три"};
    4.  
    5. /* Однако мы можем использовать константу */
    6.  
    7. const int len = 3; //Это константа
    8. //А теперь скомпилируется
    9. string[] Privet = new string[len] {"раз", "два", "три"};


    What is interesting to do with the array?
    Find out the length of the array:
    1. int Dlina = Massiv.Length;
    2. //ToString() - переводит из int в string
    3. Console.WriteLine(Dlina.ToString());

    Sort:
    1. //Наш массив передаётся в качестве параметра методу Sort()
    2. Array.Sort(Massiv);

    We change the order:
    1. //Наш массив передаётся в качестве параметра методу Reverse()
    2. Array.Reverse(Massiv);

    and much more ... I

    recommend reading about multidimensional arrays in a book yourself.

    So for today I think enough. You won’t believe it, but I missed one day due to the fact that after I printed this (similar) article in the HabrRedactor, the browser turned off something and I did not manage to save it. I got very angry and went to sleep. Emotions ...

    Also popular now: