Alex Rivera | Logout

Private Set or Private member?

Asked 2011-03-01T21:26:09.000
21

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

       public int PublicGetPrivateSetter
       {
            get;
            private set;
        }

        private int _privateMember;

        public int PublicGetPrivateMember
        {
            get { return _privateMember; }
        }

I feel that using a private member is more explicit in your code that it's a private setter (using naming conventions). On the other hand using private setters gives you an option to use virtual (protected), write less code, has less room for mistakes and can give you an option to add a side effect later on if you need to.

I couldn't find what's considered a best practice, or even if one is considered better than the other. From what I've seen usually 80% of the time (from code that I'VE seen) people DONT use private setters... I'm not sure if this is because people don't know about private setters, or because it's considered better to actually use private members.

EDIT:

Indeed, other benefits which I forgot about when using private members is default values and the use of readonly.

Edit
Report

1 Answer

0

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.

answered 2011-03-01T21:29:22.497

Your Answer