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);
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.
-
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() { MyProp="primo"; }; //instance.MyProp="secondo"; instance.Show(); class Program { /*--IF WE WANT MYPROP TO BE READ ONLY WE CAN DELETE THE SET FROM THE PROPERTY. HOWEVER, SOMETIMES THERE IS A NEED TO RENDER A READ-ONLY PROPERTY BUT INITIALIZED TO A VALUE. TO DO THIS JUST ADD THE KEYWORD INIT IN THE SETTER. THE PROPERTY IS CALLED IMMUTABLE AS IT CAN BE INITIALIZED ONLY ONCE.*/ public string MyProp {get;init;} public void Show() { Console.WriteLine($"MyProp = {MyProp}"); } }
-
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 { public string Titolo {get;init;} public string Autore {get;init;} public Libro() { } public Libro(string titolo, string autore) { Titolo=titolo; Autore=autore; } }
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:
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 {Autore = "Giulio Verne"}; //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);
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.
Once the extension is installed, press F1 and create a new notebook.
- 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 ({Lenght:>=20 } And {Length:<=200}))
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 { FirstName = John, LastName = Doe }
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 { LastName = “Smith” };
Console.WriteLine(person2); // Output: Person { FirstName = John, LastName = Smith }
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
{
public string Make { get; init; }
public string Model { get; init; }
}
Positional Records vs. Records with Members
In addition to the positional statement, records can be defined as classes with members:
public record Book
{
public string Title { get; init; }
public string Author { get; init; }
public Book(string title, string author)
{
Title = title;
Author = author;
}
}
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
{
public static void Main()
{
var student1 = new Student(“John”, “Doe”, “High School“);
var student2 = student1 with { LastName = “Smith” };
Console.WriteLine(student1); // Output: Student { FirstName = John, LastName = Doe, School = High School }
Console.WriteLine(student2); // Output: Student { FirstName = John, LastName = Smith, School = High School }
Console.WriteLine(student1 == student2); // Output: False
}
}
Leave A Comment