You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
// ========================================================================
|
|
|
|
|
//
|
|
|
|
|
// Copyright (C) 2016-2017 MARC CHEVALDONNE
|
|
|
|
|
// marc.chevaldonne.free.fr
|
|
|
|
|
//
|
|
|
|
|
// Module : Program.cs
|
|
|
|
|
// Author : Marc Chevaldonné
|
|
|
|
|
// Creation date : 2016-09-23
|
|
|
|
|
//
|
|
|
|
|
// ========================================================================
|
|
|
|
|
|
|
|
|
|
using System;
|
|
|
|
|
using static System.Console;
|
|
|
|
|
|
|
|
|
|
namespace ex_012_001_nullableTypes
|
|
|
|
|
{
|
|
|
|
|
class Program
|
|
|
|
|
{
|
|
|
|
|
//les types référence peuvent représenter une valeur non-existante (null reference)
|
|
|
|
|
//par contre, les valeurs elles, ne le peuvent pas : int i = null n'est pas autorisé
|
|
|
|
|
//En C# on peut quand même le faire, à l'aide des nullable types
|
|
|
|
|
static void Main(string[] args)
|
|
|
|
|
{
|
|
|
|
|
int? i = null;
|
|
|
|
|
WriteLine("int? i = null");
|
|
|
|
|
Write("i == null ? ");
|
|
|
|
|
WriteLine(i == null);
|
|
|
|
|
WriteLine($"i.HasValue {i.HasValue}");
|
|
|
|
|
WriteLine($"i or default : {i.GetValueOrDefault()}");
|
|
|
|
|
i = 2;
|
|
|
|
|
WriteLine("i = 2");
|
|
|
|
|
Write("i == null ? ");
|
|
|
|
|
WriteLine(i == null);
|
|
|
|
|
WriteLine($"i.HasValue {i.HasValue}");
|
|
|
|
|
WriteLine($"i or default : {i.GetValueOrDefault()}");
|
|
|
|
|
WriteLine($"i.Value : {i.Value}");
|
|
|
|
|
|
|
|
|
|
//l'opérateur ?? est le null coalescing operator
|
|
|
|
|
int? x = null;
|
|
|
|
|
int y = x ?? 5; // y vaut 5 car x est null
|
|
|
|
|
int? a = 1;
|
|
|
|
|
int? b = 2;
|
|
|
|
|
int? z = x ?? a ?? b; // y vaut 1 car a est la première valeur non nulle
|
|
|
|
|
int? c = null;
|
|
|
|
|
int? w = x ?? c ?? b; // y vaut 2 car b est la première valeur non nulle
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|