C SHARP 9

  • TOP LEVEL STATEMENT

We write the usual Console program using the command line dotnet new console -o TopLevelStatement.

using System;
               /*We loop through all arguments passed from the command line
                to the string array args. Once this is done, let's eliminate the namespace, 
                the program class and the Main method from the program. The usefulness of the 
                top level statement can be seen at an educational level.*/
            foreach (var item in args)
               Console.WriteLine(item);

Top level statement

The program works just the same and nothing magical happened, it is the compiler who created the Program class, the Main method and the namespace behind the scenes.

Top level statement

  • INIT ONLY SETTERS

This new feature of the language allows us to use properties that are read-only but can be initialized.

using System;

    var instance = new Program()
    ;
    //instance.MyProp="secondo";
    instance.Show();
    class Program
    

  • RECORD

The Records are an important addition to the C # language as you can use the reference types with a semantics typical of the value types in particular for equality, moreover the Records are used to create immutable entities.

DATA MODEL 

When we talk about Data Model we do it by referring to a particular Data Type that we introduce in one of our programs. It is usually implemented as a class or structure. A Data Model has the particularity of representing information consisting mainly of data without functionality. Furthermore, the instances of a Data Model are considered immutable, that is, once we have initialized all the properties, they should be immutable to obtain a solidity and consistency of the data.

using System;
    
    Libro libro1 = new Libro("L'isola misteriosa","Jules Verne");
    Libro libro2 = new Libro("L'isola misteriosa","Jules Verne");
    //Libro libro2 = new Libro("Neuromante","William Gibson");
    Console.WriteLine(libro1==libro2);//FALSE (TRUE con record)
    Console.WriteLine(libro1);//LIBRO
    /*--From the Console we receive False and 
        Libro this because the comparison of two reference 
        types is based on references, so since there are 
        two different references pointing to libro1 and 
        libro2 the equality will be false. Also displaying 
        in the terminal the object that is associated 
        with a variable causes the execution of the 
        ToString() method of the Object class. 
        From the point of view of the Data Model 
        we have a problem, we would like the comparison 
        of two objects having the same property to give 
        True and not False. To have a behavior closer 
        to a data model we replace the keyword Class 
        with record. A record is always a reference 
        types but with particular characteristics. 
        First of all, the comparison for equality this 
        time returns true as we wanted, this is because 
        the record type used a semantics with value 
        instead of a reference and since the properties 
        are equal the comparison returns True. 
        Printing the value of libro1 to Console this 
        time the ToString method () Back Title and 
        Author of libro1 */
    
    record Libro
    

POSITIONAL SYNTAX

We have written a record that represents a hypothetical Data Model of a book. With positional syntax we can take out a lot of the code and simply write:

record Libro(string Titolo, string Autore);

The initial part of the declaration remained intact we used the keyword record and the Book Type, then we introduced in brackets the properties we want to assign to our record. Obviously it's the compiler behind the scenes doing the work for us, specifically:

record

By running this line of code, the result remains unchanged.

NON-DESTRUCTIVE MODIFICATION

using System;
Libro libro1 = new Libro("L'isola misteriosa","Jules Verne");
Libro libro2 = libro1 with ;
//libro1.Autore="Pippo"; //ERRORE
/*--Sometimes it can be useful to modify a 
property, to do this C # provides us with a 
method of duplicating the record during which 
the properties can be modified. To duplicate a 
record that we repeat is a reference types, the 
assignment operator is not enough, but to double 
the references and therefore modify their 
properties, the with operator must be used. 
Once you have changed the properties you need 
to change libro2 is again an immutable type.*/
Console.WriteLine(libro2.Autore);
record Libro(string Titolo, string Autore);

operatore with

INHERITANCE

using System;
Libro libro1 = new Libro("L'isola misteriosa","Jules Verne");
LibroDigitale libro2 = new LibroDigitale("Neuromante","William Gibson&quot","8 ore");
Console.WriteLine(libro1);
Console.WriteLine(libro2);
record Libro(string Titolo, string Autore);
record LibroDigitale(string Titolo, string Autore, string Durata):Libro(Titolo,Autore);

NET INTERACTIVE NOTEBOOKS

It is a learning tool, similar to Phyton’s. You need to install the extension shown in the figure, the latest version of visual studio code and .NET 5.0 latest release.

Interactive

Once the extension is installed, press F1 and create a new notebook.

Example Interactive
  • TARGET-TYPED NEW

List<int> myInt = new List<int>();

In C# 9 possiamo semplificare la sintassi.

List<int> myInt = new();

  • NUOVE KEYWORD AND OR E NOT

if(Title is "MyTytle" or not ( And ))

    Throw(new ArgumentException("Title is not valid");

DEEPENING

Records in C# 9.0 represent one of the most interesting new features introduced to the language. They provide a concise, declarative way to define immutable data types. Let's look at a detailed description of how they work and how they can be used:

Defining a Record

A record in C# is defined with the record keyword. Here is an example of a record representing a person:

public record Person(string FirstName, string LastName);

Main Characteristics of Records

1. Immutability:

– Record properties are generally immutable by default. You can change this setting using init setters.

2. Automatic Method Generation:

– C# automatically generates methods such as Equals, GetHashCode, and ToString for records based on property values.

– Example:

var person1 = new Person("John", "Doe");
var person2 = new Person("John", "Doe");
Console.WriteLine(person1 == person2); // Output: True
Console.WriteLine(person1); // Output: Person

3. Expression with:

– Allows you to create a copy of a record with some modifications:

var person1 = new Person("John", "Doe");
var person2 = person1 with ;
Console.WriteLine(person2); // Output: Person

5. Inheritance:

– Records can participate in inheritance like classes.

public record Employee(string FirstName, string LastName, string Position) : Person(FirstName, LastName);

Advanced Use of Records

Properties init-only

Properties can be initialized only during object creation or through the with expression:

public record Car

Positional Records vs. Records with Members

In addition to the positional statement, records can be defined as classes with members:

public record Book

Complete Example

Here is a more complete example showing several features of the records:

public record Person(string FirstName, string LastName);

public record Student(string FirstName, string LastName, string School) : Person(FirstName, LastName);

public class Program

   

      LINK TO PREVIOUS POST

LINK TO THE CODE ON GITHUB