Correct use of C# properties

后端 未结 12 631
生来不讨喜
生来不讨喜 2020-12-16 15:19
private List _dates;

public List Dates
{
    get { return _dates; }
    set { _dates = value; }
}

OR

publi         


        
相关标签:
12条回答
  • 2020-12-16 15:52

    I believe they compile to the same code. The latter is just syntactic sugar to represent the former. I tend to think of the latter as a placeholder for future logic that may need to be placed in the properties, at which point I'd convert said affected properties to the former.

    0 讨论(0)
  • 2020-12-16 15:56

    Use the former if you need to add some kind of logic to your getter/setters.

    Use the latter otherwise. It makes things much cleaner. You can also achieve read-only properties using auto properties:

    public List<Date> Dates { get; private set; }
    

    Or, if you don't want people to add any items to the list through the property you can resort to the former syntax:

    private List<Date> _dates = new List<Date>();
    private ReadOnlyCollection<Date> _readOnlyDates =
        new ReadOnlyCollection<Date>(_dates);
    
    public ReadOnlyCollection<Date> Dates
    {
        get { return _readOnlyDates; }
    }
    
    0 讨论(0)
  • 2020-12-16 15:56

    The two are compiled roughly the same way (I don't know that the backing field's name would specifically be the same, but they'd be functionally equivelant).

    IIRC, the ability to do Automatic Properties (public List<Date> Dates {get; set;}) was added in either .NET 3.0 or 3.5.

    0 讨论(0)
  • 2020-12-16 16:04

    Both are basically the same because of how .NET compiles automatic properties. Automatic properties became available with .NET 3.5.

    0 讨论(0)
  • 2020-12-16 16:05

    It doesn't matter. The second is just sugar. I always use the second because it's cleaner, but every once in a while I need access to the backing value.

    0 讨论(0)
  • 2020-12-16 16:06

    They are equivalent in the internal compiled form, except that you cannot access the compiler generated private variable in the second form.

    From a code efficiency point of view, they are equivalent as well, the just in time compiler normally directly accesses the private variable without the overhead of calling an access function (after the runtime environment has checked accessibility etc.).

    From a coding perspective, I prefer the second version which is more compact (less to write, less to read).

    The second syntax was introduced in C# 3.0. So the first variant would be more compatible to old compilers.

    0 讨论(0)
提交回复
热议问题