2023/11/8–C#–Structures, enumerations, delegates…

1. Structure:

In C#, a structure (struct) is a user-defined value type used to encapsulate a set of related data fields. Unlike classes, structures are value types, while classes are reference types. This means that instances of structures are copied when assigned to variables, passed to methods, or passed as function arguments, whereas instances of classes are passed by reference.

C# Structure (Struct)
1. A structure is a value type data structure.
2. Reference types are derived from System.Object, while value types are implicitly derived from System.ValueType
3. The struct keyword is used to create a structure
4. Structures can have methods, fields, properties, operators, delegates and events.
5. The structure can implement one or more interfaces but cannot inherit other classes.
6. The structure does not support being inherited by other classes.
7. Structure members cannot be specified as virtual or protected.
8. The structure can use New to create objects or not. If there are attributes in the structure, new must be used to create objects.
Numeric types

The difference between classes and structures:

1. Classes and structures are actually templates for creating objects. Each object contains data and provides methods for processing and accessing data.
2. Classes are reference types, objects are stored in the heap, and memory can be managed through GC. Structures are value types, and objects are stored in the stack.
3 Structures cannot be inherited, nor can they inherit from other classes, but they can inherit interfaces.
4. Both structures and classes can use new to create objects, but structures can also be used without it.
5. When a structure is used as a method parameter, it is passed by value by default. For class types, it is passed by reference by default.

1. Declaration of structure: Structure is declared using the struct keyword. Here is an example of a simple structure:

struct Point
{
    public int X;
    public int Y;
}

In the above example, Point is a structure with two integer fields X and Y.

2. Default constructor: The structure has no implicit parameterless constructor. Therefore, you must provide initial values for the fields of the structure. If no constructor is provided, the field will be initialized to a default value (usually zero or null, depending on the field’s data type).

3. Custom constructor: You can define your own constructor for a structure to provide initial values when creating an instance. For example:

struct Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }
}

4. Methods: Structures can contain methods that allow you to perform operations on the structure. Methods can modify the values of fields of a structure. But be aware that when you pass structs as parameters, they are passed by value, so changes to the struct in the method will not affect the original instance.

struct Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public void Move(int deltaX, int deltaY)
    {
        X + = deltaX;
        Y + = deltaY;
    }
}

5. Use structures: You can use structures just like other data types. Here are some examples of using structs:

Point p1 = new Point(10, 20);
Point p2 = p1; // p2 is a copy of p1, not a reference
p2.Move(5, 5); // Modifying p2 will not affect p1

Console.WriteLine($"p1: X={p1.X}, Y={p1.Y}"); // Output p1: X=10, Y=20
Console.WriteLine($"p2: X={p2.X}, Y={p2.Y}"); // Output p2: X=15, Y=25

In short, structures are used in C# to create lightweight value types, usually used to represent simple data structures. They are suitable for allocating memory on the stack rather than on the heap, which can improve performance and reduce garbage collection pressure. Structures are suitable for small data objects, while classes are better suited for complex objects and situations where reference semantics are required.

2. Enumeration:

In C#, an enumeration (Enum) is a user-defined data type used to represent a set of named integer constants. Enumeration types allow you to define a set of related constant values that are readable in code without having to remember their actual integer values.

An enumeration is a structure that describes a set of integer values to make numbers more concrete.
Enums are value types
Enumeration types are declared using the enum keyword
An enumeration is a set of integer constants. The default is to start from 0. You can also define the range yourself.
The enumeration itself can have modifiers, but the members of the enumeration are always public,
There cannot be access modifiers. The modifiers of the enumeration itself can only use public and internal.
Enumerations are implicitly sealed and are not allowed to be derived from base classes

1. Declaration of enumeration: Enumeration is declared using the enum keyword.

enum DaysOfWeek
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

In the above example, DaysOfWeek is an enumeration type that contains a set of constants representing the days of the week.

2. The default underlying type of the enumeration: The constant values of the enumeration are all integers internally, and they have a default underlying integer type. By default, it is int, but you can explicitly specify other integer types, such as byte, short, long code>etc. For example:

enum Status: byte
{
    Inactive,
    Active,
    Suspended
}

3. Access enumeration members: You can use members of the enumeration type to access the constant values of the enumeration, for example:

DaysOfWeek today = DaysOfWeek.Wednesday;
Console.WriteLine(today); // Output Wednesday

4. Use enumerated constant values: Enumerated constant values can be used in conditional statements, loops, and other code to increase readability. For example:

DaysOfWeek today = DaysOfWeek.Friday;

if (today == DaysOfWeek.Saturday || today == DaysOfWeek.Sunday)
{
    Console.WriteLine("It's the weekend!");
}
else
{
    Console.WriteLine("It's a weekday.");
}

5. Get the integer value of the enumeration: You can use the ToInt32 method of the enumeration member to get the integer value of the enumeration, or use type conversion. For example:

int sundayValue = (int)DaysOfWeek.Sunday;
int mondayValue = (int)DaysOfWeek.Monday;

Console.WriteLine(sundayValue); // Output 0
Console.WriteLine(mondayValue); // Output 1

6. Bit Flag Enums for Enumerations: You can also create bit flag enumerations that allow the constant values of the enumeration to be combined together. This is useful for flags representing multiple options. For example:

[Flags]
enumPermissions
{
    None = 0,
    Read = 1,
    Write = 2,
    Delete = 4,
    Execute = 8
}

Permissions myPermissions = Permissions.Read | Permissions.Write;

In summary, an enumeration is a data type that helps increase the readability and maintainability of your code, especially when you need to represent a set of related constant values. They are often used to represent discrete options or states.

3. Delegate:

In C#, a delegate is a type that allows you to pass a method as a parameter or store a method reference in a variable. Delegates are used to implement dynamic invocation of callback methods, event handling, and delegate methods, making the code more flexible and extensible.

Here are some key concepts and examples about C# delegates:

1. Declaration of delegates: A delegate is a type that defines the signature of a method that can be referenced. The delegate declaration includes the return type and parameter list. For example, the following is an example of a delegate declaration:

delegate void MyDelegate(int x, int y);

This delegate can reference a method that accepts two integer parameters and has a return type of void.

2. Instantiation of delegates: You can instantiate a delegate and bind a method to it. This way, the delegate can call the method. For example:

MyDelegate myDelegate = SomeMethod;

Here, SomeMethod is a method whose signature matches the signature of MyDelegate.

3. Calling of delegates: You can use delegates to call bound methods, just like calling ordinary methods:

myDelegate(10, 20);

This will call the bound method SomeMethod, passing parameters 10 and 20.

4. Multicast delegates: Delegates also support multicast, which means you can bind multiple methods to the same delegate and they will be executed in the order they are added. For example:

myDelegate + = AnotherMethod; myDelegate(10, 20);

This will first call SomeMethod and then AnotherMethod.

5. Anonymous methods and Lambda expressions: C# also introduces anonymous methods and Lambda expressions, which make the use of delegates more convenient. For example, use a Lambda expression to create a delegate:

MyDelegate add = (x, y) => Console.WriteLine(x + y); add(10, 20);

6. Built-in delegates: C# also provides some built-in general delegates, such as Action and Func, which are used to represent functions without return values. Methods and methods with return values. These generic delegates can be used to simplify your code.

Action printSum = (x, y) => Console.WriteLine(x + y); Func add = (x, y) => x + y; code>

Delegates are a very powerful and important feature in C#. They allow you to write more scalable and maintainable code, especially in terms of event handling, callback mechanisms and dynamic method invocation.