Example #1
0
        private static void NullableStructures()
        {
            PointVal pv;
            // Console.WriteLine(pv.X); // Not initialized
            PointRef pr = null;
            // Console.WriteLine(pr.X); // Null Pointer Exception

            PointVal?pv2 = null;

            if (pv2.HasValue)
            {
                PointVal pv3 = pv2.Value;
                Console.WriteLine(pv2.Value.X);
                Console.WriteLine(pv3.X);
            }

            PointVal pv4 = pv2.GetValueOrDefault();
        }
Example #2
0
        private static void BoxingAndUnboxing()
        {
            int    x   = 1;
            object obj = x;    // Boxing

            int y = (int)obj;  // Unboxing

            double pi   = 3.14;
            object obj2 = pi;

            // double number = (int) obj2;      // Invalid Cast Exception
            double number = (int)(double)obj2;  // Possible workaround

            Console.WriteLine(number);

            var point = new PointRef();

            DoSomething(point);
            Console.WriteLine($"PointRef: x={point.X}, y={point.Y}");
        }
Example #3
0
        private static void DoSomething(object o)
        {
            if (o is PointRef)
            {
                PointRef pr = (PointRef)o;
                pr.X = 11;
                pr.Y = 22;
            }

            PointRef pr2 = o as PointRef;

            if (pr2 != null)
            {
                // Do Something
            }

            if (o is PointRef pr3)
            {
                // Do Something
            }
        }