using System; namespace DemoTypes { struct Point { public int X, Y; public Point(int X, int Y) { this.X = Y; this.Y = Y; } } static class NullableDemo { public static void DoDemo() { Console.WriteLine("\nNullableDemo"); Console.WriteLine("------------------------------------------------------"); // To declare a nullable variable, append ? to value-type name. int? myNullableInt; // Nullable primitive. Point? myNullablePoint; // Nullable struct. DayOfWeek? myNullableDow; // Nullable enum. // Alternative syntax. // Nullable myNullableInt2; // Nullable myNullablePoint2; // Nullable myNullableDow2; // You can assign null to any nullable-type variable. myNullableInt = null; // Converts null to int? myNullablePoint = null; // Converts null to Point? myNullableDow = null; // Converts null to DayOfWeek? // .NET allows implicit conversion from T to T? myNullableInt = 10; // int to int? myNullablePoint = new Point(10, 20); // Point to Point? myNullableDow = DayOfWeek.Friday; // DayOfWeek to DayOfWeek? DisplayValues(myNullableInt, myNullablePoint, myNullableDow); } private static void DisplayValues(int? myNullableInt, Point? myNullablePoint, DayOfWeek? myNullableDow) { // Nullable types provide the HasValue and Value properties. if (myNullablePoint.HasValue) { Point p = myNullablePoint.Value; Console.WriteLine("X coordinate: " + p.X); Console.WriteLine("Y coordinate: " + p.Y); } else { Console.WriteLine("No Point value at the moment"); } if (myNullableInt.HasValue) { Console.WriteLine("Integer value: " + myNullableInt.Value); } else { Console.WriteLine("No integer value at the moment"); } if (myNullableDow.HasValue) { Console.WriteLine("DayOfWeek value: " + myNullableDow.Value); } else { Console.WriteLine("No DayOfWeek value at the moment"); } } } }