Advertisement
fcamuso

C# 9, init only setters

Dec 15th, 2021
885
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.12 KB | None | 0 0
  1. using System;
  2.  
  3. namespace init_record
  4. {
  5.     class Galassia
  6.     {
  7.         private readonly string _codiceNGC;
  8.         private readonly double _distanza;
  9.  
  10.         public string CodiceNGC { get; init; }        
  11.         public double Distanza {
  12.             get => Distanza;
  13.             init
  14.             {
  15.                 if (value < 0) throw new ArgumentOutOfRangeException();
  16.                 _distanza = value;
  17.             }
  18.  
  19.          } //milioni di anni luce
  20.  
  21.         //public Galassia(string CodiceNGC, double Distanza)
  22.         //{
  23.         //    this.CodiceNGC = CodiceNGC;
  24.         //    this.Distanza = Distanza;
  25.         //}
  26.  
  27.     }
  28.  
  29.     internal class Program
  30.     {
  31.         static void Main(string[] args)
  32.         {
  33.             //Galassia andromeda = new Galassia("224", 2.537);
  34.             //andromeda.CodiceNGC = "224";
  35.             //andromeda.Distanza = 2.537;
  36.  
  37.             Galassia andromeda = new Galassia
  38.             {
  39.                 CodiceNGC = "224",
  40.                 Distanza = -2.537
  41.             };
  42.  
  43.             //andromeda.CodiceNGC = "sadlfjdo"; NO! Read Only ...
  44.  
  45.         }
  46.     }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement