Private Set or Private member?

前端 未结 7 2200
旧时难觅i
旧时难觅i 2020-12-29 05:05

I was wondering what\'s considered the C# best practice, private/protected members with public getters, or public getters with private/protected setters?

            


        
相关标签:
7条回答
  • 2020-12-29 05:30

    Its the same thing. In the first example, the compiler generates the backing store. In the second, you generated the backing store. Since the implementation is internal to the class, refactoring one into the other is not a big deal. Tools like Resharper make that trivial. The reason you probably haven't seen private setters that much is that its a C# 3.0 feature.

    0 讨论(0)
  • 2020-12-29 05:33

    There is no good answer to this question. the best pratice is to follow our compagnie nomenclature and if your alone then the way you prefer

    0 讨论(0)
  • 2020-12-29 05:34

    There's nothing wrong with private setters. In most case, it's used with auto properties to make the property readonly outside the object's scope.

    0 讨论(0)
  • 2020-12-29 05:34

    Conceptualy speaking, it doesn't change anything. It's mostly a matter of taste.

    I personnally use the private setter because I'm lazy and use the propg snippet a lot. (propg tab tab)

    Also, most of the time I end up setting dirty flags and binding events to those properties, so I might as well do a part of the work right now. If you ever need to add a setter later, it's much easier if the code is written without using the member behind since the beggining as it will be less code to change.

    0 讨论(0)
  • 2020-12-29 05:38

    I prefer to use auto-implemented properties unless the default implementation doesn't do what I want. So in this case, since the auto-implemented property does what you need, just use that:

    public int Foo { get; private set; }
    

    However another situation is if you want to make the field readonly (meaning that the only place where the field can be set is in the constructor). Then you need to define the backing field and mark it readonly as this isn't supported by auto-implemented properties:

    private readonly int foo;
    
    public int Foo
    {
        get { return foo; }
    }
    
    0 讨论(0)
  • 2020-12-29 05:38

    There is no best practice I'm aware of. I know automatic properties were mainly to make things easier even more easier for code generation and LINQ related stuff.

    For me, I start with automatic properties and refactor later if needed. Depending on the need I may change something to virtual or protected as you mentioned, or maybe refactor to use a variable (When I want to refactor the set accessor to have some logic.

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