What is the best way to give a C# auto-property an initial value?

前端 未结 22 3000
死守一世寂寞
死守一世寂寞 2020-11-22 02:48

How do you give a C# auto-property an initial value?

I either use the constructor, or revert to the old syntax.

Using the Constructor:

22条回答
  •  粉色の甜心
    2020-11-22 03:18

    I know this is an old question, but it came up when I was looking for how to have a default value that gets inherited with the option to override, I came up with

    //base class
    public class Car
    {
        public virtual string FuelUnits
        {
            get { return "gasoline in gallons"; }
            protected set { }
        }
    }
    //derived
    public class Tesla : Car
    {
        public override string FuelUnits => "ampere hour";
    }
    

提交回复
热议问题