Elegant way of reading a child property of an object

前端 未结 11 1191
半阙折子戏
半阙折子戏 2020-12-24 02:19

Say you are trying to read this property

var town = Staff.HomeAddress.Postcode.Town;

Somewhere along the chain a null could exist. What wo

11条回答
  •  攒了一身酷
    2020-12-24 02:22

    @Oded's and others' answers still hold true in 2016 but c# 6 introduced the null-conditional operator which provides the elegance you are after.

    using System;
    
    public class Program
    {
        public class C {
            public C ( string town ) {Town = town;}
            public string Town { get; private set;}
        }
        public class B {
            public B( C c ) {C = c; }
            public C C {get; private set; }
        }
        public class A {
            public A( B b ) {B = b; }
            public B B {get; private set; }
        }
        public static void Main()
        {
            var a = new A(null);
            Console.WriteLine( a?.B?.C?.Town ?? "Town is null.");
        }
    }
    

提交回复
热议问题