using System;
Persona p = new Persona("Mario","Rossi");
Console.WriteLine(p.Denominazione);

struct Persona
{
    private string nome;
    private string cognome;

    public Persona(string nome, string cognome)
    {
        this.nome = nome;
        this.cognome = cognome;
    }
    public string Denominazione => this.nome + " " + this.cognome;
}

THE STRUCTS IN C SHARP

C sharpStructs in c sharp are structures similar to classes, but there are also profound differences that we will explore in a bit.
A struct can contain variables, methods, properties. The first difference that jumps out at you when looking at the code below is the struct keyword instead of class, but let’s look at the differences with classes:

  • The first and most significant is that structs are value types, unlike classes which are reference types.
  • Structs admit constructors like classes in which to initialize variables but do not have the parameterless constructor.
  • Structs do not support inheritance, the second pillar after encapsulation in Object Oriented programming.
  • The attributes of structs must be explicitly initialized.

INITIALIZE STRUCTS

We define a struct representing the concept of a person, with two attributes first name and last name.
If somewhere else in the program we define the struct as Person p; we have a small problem, namely, the fields of the Struct are not initialized even to their default values.
It is we who must explicitly initialize them. Nothing prevents us from using a constructor with parameters to initialize all the fields of the struct. At the end of these discussions we must ask ourselves when to use a struct or a class? A struct is fine for defining simple data, not too articulate, let us remember that it is a Value Types, so if the struct is to be passed as a parameter to a method if too large it would result in inefficiency in terms of memory occupancy.

PRIMITIVE TYPES ARE STRUCTS

Let us conclude the struct argument by saying that all the primitive types seen so far except string are structs, int is just an alias while the real name of the struct is Int32. Declaring int x = 0; or Int32 x = 0; is perfectly equivalent. The same applies to the other primitive types.

using System;
namespace Struct
{
    class Program
    {
        static void Main(string[] args)
        {
            Azienda azienda = new Azienda("Pippo S.P.A",100,100_000_000); //INIZIALIZZAZIONE CON COSTRUTTORE
            Azienda a = new Azienda();//VENGONO INIZIALIZZATI GLI ATTRIBUTI DELLA STRUCT AI LORO VALORI DI DEFAULT.
            a.Fatturato=200_000_000m;
            Persona persona;  //LE VARIABILI DELLA STRUCT PERSONA NON SONO INIZIALIZZATE AI LORO VALORI DI DEFAULT
                              //A DIFFERENZA DELLE CLASSI.
            persona.nome="Marco";
            persona.cognome="Rossi";
            //ESERCITAZIONE CON LE STRUCT
            MyClass mc = new MyClass();
            MyStruct ms = new MyStruct();
            mc.eta=40;
            mc.nome="Mario";
            ms.eta=60;
            ms.nome="Fabio";
            Console.WriteLine($"Prima della chiamata mc.eta=: {mc.eta} ms.eta=: {ms.eta}");
            MyMethod(mc,ms,"Pippo",20);
            Console.WriteLine($"Dopo la chiamata mc.eta=: {mc.eta} ms.eta=: {ms.eta}");
            /*--LE STRUCT ESSENDO DEI VALUE TYPES PASSANO AL METODO UNA COPIA DEI LORO ATTRIBUTI
            AL RITORNO DAL METODO I VALORI NON SONO MODIFICATI. vICEVERSA LE CLASSI ESSENDO
            DEI REFERENCE TYPES PASSANO UNA COPIA DEL RIFERIMENTO CHE PUNTA ALLA MEDESIMA STRUTTURA
            CREATA NELL'HEAP, AL RITORNO L'ISTANZA mc SARA' MODIFICATA.*/
        }
        static void MyMethod(MyClass mc, MyStruct ms, string myString, int myInt )
        {
            mc.nome=myString;
            mc.eta=myInt;
            ms.nome=myString;
            ms.eta=myInt;
        }
    }
    public struct Azienda
    {
        private string ragioneSociale;
        private int numeroDipendenti;
        public decimal Fatturato {get;set;}
 
        public Azienda(string ragioneSociale,int numeroDipendenti,decimal fatturato)
        {
            this.ragioneSociale=ragioneSociale;
            this.numeroDipendenti=numeroDipendenti;
            this.Fatturato=fatturato;
        }
    }
    struct Persona
    {
        public string nome;
        public string cognome;
    }
    public class MyClass
    {
        public string nome;
        public int eta;
    }
    public struct MyStruct
    {
        public string nome;
        public int eta;
    }
}

IN-DEPTH STUDY OF STRUCTS

In C#, structures (structs) are a data type that allows you to create complex but lightweight data types. Structs are similar to classes, but there are some key differences that make them more suitable for specific situations. Here is a simple explanation of structs in C#:

What is a Structure?

A structure is a data type that can contain fields and methods like a class, but is typically used to contain a small group of related data.
Structures are allocated in the stack, making them more efficient for small data types.

Differences between Structures and Classes

Memory allocation: Structures are allocated in the stack while classes are allocated in the heap.

Immutability: Structures are typically immutable (i.e., their values do not change after they are created).

Inheritance: Structures cannot be derived from other structures or classes (they do not support inheritance).

Default constructor: Structures have a default constructor that cannot be removed.

Statement of a Structure

Here is an example of how to declare a structure in C#:

public struct Punto
{

      public int X;
      public int Y;

      public Punto(int x, int y)
      {

          X = x;

          Y = y;

      }

      public void Muovi(int deltaX, int deltaY)
      {

          X += deltaX;

          Y += deltaY;

      }

      public override string ToString()
      {

        return $”({X}, {Y});
      }
}

Use of a Structure

Here is how to use the Punto structure defined above:

class Program
{  

    static void Main()
    {
      Punto p = new Punto(2, 3);
      Console.WriteLine(p); // Output: (2, 3)

      p.Muovi(1, 1);
      Console.WriteLine(p); // Output: (3, 4)
    }
}

Characteristics of Facilities

–  Value type: Structures are value types, so when you assign one structure to another, a copy of the values is made, not a reference.

–  Constructors: Structures can have constructors to initialize their data.

–  Methods and Properties: Structures can have methods and properties like classes.

–  Interfaces: Structures can implement interfaces.

When to Use Structures?

  • When you need a lightweight data type.
  • When it is known that the data type will not change after its creation.
  • When you want to avoid the heap allocation overhead associated with classes.

Structures are ideal for representing simple data such as points, rectangles, colors, etc., where performance and memory efficiency are crucial.

LINKS TO PREVIOUS POSTS

GITHUB CODE ASSOCIATED WITH THE COURSE