C# Automatic Properties - Why Do I Have To Write “get; set;”?

后端 未结 9 1921
失恋的感觉
失恋的感觉 2020-12-29 01:33

If both get and set are compulsory in C# automatic properties, why do I have to bother specifying \"get; set;\" at all?

9条回答
  •  情话喂你
    2020-12-29 01:49

    Also, because ever since C# 6.0 (in Visual Studio 2015, at the time of this answer available in version Ultimate Preview) you may implement a true read-only property:

    public string Name { get; }
    public string Name { get; } = "This won't change even internally";
    

    ... as opposed to currently imperfect workaround with public getter/private setter pair:

    public string Name { get; private set; }
    
    public Constructor() { Name="As initialised"; }
    public void Method() { Name="This might be changed internally. By mistake. Or not."; }
    

    Example of the above below (compiled and executable online here).

    using System;
    
    public class Propertier {
        public string ReadOnlyPlease { get; private set; }
    
        public Propertier()  { ReadOnlyPlease="As initialised"; }
        public void Method() { ReadOnlyPlease="This might be changed internally"; }
        public override string ToString() { return String.Format("[{0}]",ReadOnlyPlease); }
    }
    
    public class Program {
        static void Main() {
            Propertier p=new Propertier();
            Console.WriteLine(p);
    
    //      p.ReadOnlyPlease="Changing externally!";
    //      Console.WriteLine(p);
    
            // error CS0272: The property or indexer `Propertier.ReadOnlyPlease' cannot be used in this context because the set accessor is inaccessible
            // That's good and intended.
    
            // But...
            p.Method();
            Console.WriteLine(p);
        }
    }
    

    Other tasty news about C# 6.0 available as official preview video here.

提交回复
热议问题