Advertisement
fcamuso

Nullable value/reference type

Apr 13th, 2021
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.52 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Nullable_1
  4. {
  5.   class Program
  6.   {
  7.     class Razzo
  8.     { int AccelerazioneDaFermo { get; set; } // m/sec2
  9.  
  10.       public Razzo(int accelerazioneDaFermo)
  11.       { AccelerazioneDaFermo = accelerazioneDaFermo; }
  12.  
  13.       public double? Tempo(int velocita)
  14.       {
  15.         try { return velocita / AccelerazioneDaFermo; }
  16.  
  17.         catch (DivideByZeroException e)
  18.         { /*Console.WriteLine("Classe Razzo, metodo Tempo: divisione per zero\n");*/ }
  19.  
  20.         finally { /*Console.WriteLine("Finally eseguito");*/ }
  21.  
  22.         return null;
  23.       }
  24.     }
  25.  
  26.     static void Main(string[] args)
  27.     { Razzo apollo = new Razzo(0);
  28.  
  29.       double? t = apollo.Tempo(10000);
  30.       //if (t!=null)
  31.       //  Console.WriteLine($"Servono {t} secondi per ...\n");
  32.  
  33.       //conversione da T a T?
  34.       double x = 3.14;
  35.       t = x; //conversione implicita
  36.  
  37.       t=99;
  38.       //conversione da T? a T
  39.       //x = (double)t;  //richiede cast ma anche un controllo!
  40.  
  41.       //oppure
  42.       x = t ?? 0;
  43.       //Console.WriteLine(x);
  44.  
  45.       string? password = null;
  46.  
  47.       int? lunghezzaSenzaSpazi = password?.Trim().Length;
  48.       int? nullable1 = 100, nullable2 = 200, nullable3 = null; ;
  49.       int  nonNullable = 300;
  50.  
  51.       if (nullable2 > nullable1) Console.WriteLine("Test 1 VERO");
  52.       if (nonNullable > nullable2) Console.WriteLine("Test 2 VERO");
  53.  
  54.       if (nullable3 == null) Console.WriteLine("Test 3 VERO");
  55.       if (nonNullable > nullable3) Console.WriteLine("Test 4 VERO");
  56.  
  57.  
  58.  
  59.     }
  60.   }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement