Advertisement
fcamuso

C# 9, records

Dec 24th, 2021
886
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1. using System;
  2.  
  3. namespace records
  4. {
  5.     class AutomobileClass
  6.     {
  7.         public string Marca { get; set; }
  8.         public string Modello { get; set; }
  9.     }
  10.  
  11.     struct AutomobileStruct
  12.     {
  13.         public string Marca { get; set; }
  14.  
  15.         public string Modello { get; set; }
  16.     }
  17.  
  18.  
  19.     record Automobile(string Marca, string Modello);
  20.  
  21.     internal class Program
  22.     {
  23.         static void Main(string[] args)
  24.         {
  25.             AutomobileClass autoClass1 =
  26.                 new AutomobileClass { Marca="Fiat", Modello = "500" };
  27.             AutomobileClass autoClass2 =
  28.                 new AutomobileClass { Marca = "Fiat", Modello = "500" };
  29.  
  30.             AutomobileClass autoClass3 = autoClass1;
  31.             autoClass3.Marca = "Mercedes";
  32.             Console.WriteLine(autoClass1.Marca);
  33.  
  34.             AutomobileStruct autoStruct1 =
  35.                 new AutomobileStruct { Marca = "Fiat", Modello = "500" };
  36.             AutomobileStruct autoStruct2 =
  37.                 new AutomobileStruct { Marca = "Fiat", Modello = "500" };
  38.  
  39.             AutomobileStruct autoStruct3 = autoStruct1;
  40.             autoStruct3.Marca = "Mercedes";
  41.             Console.WriteLine(autoStruct1.Marca);
  42.  
  43.             Console.WriteLine(autoClass1.Equals(autoClass2));
  44.             Console.WriteLine(autoStruct1.Equals(autoStruct2));
  45.  
  46.             Automobile auto1 = new Automobile("Fiat", "500");
  47.             Automobile auto2 = new Automobile("Fiat", "500");
  48.  
  49.             Console.WriteLine(auto1.Equals(auto2));
  50.             Console.WriteLine(auto1 == auto2);
  51.  
  52.             //auto1.Marca = "Mercedes";  NO, immutable!
  53.  
  54.             Console.WriteLine(auto1.ToString());
  55.  
  56.             Automobile auto3 = auto1 with { };
  57.             auto3 = auto3 with { Marca = "Honda" };
  58.  
  59.             Console.WriteLine($"{auto1.Marca} {auto3.Marca}");
  60.  
  61.             var (marca, modello) = auto3;
  62.             Console.WriteLine($"{marca}, {modello}");
  63.         }
  64.     }
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement