Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private Set or Private member?

Tags:

c#

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.

like image 785
Linkgoron Avatar asked Mar 01 '11 21:03

Linkgoron


People also ask

What is a private set?

Private set intersection is a secure multiparty computation cryptographic technique that allows two parties holding sets to compare encrypted versions of these sets in order to compute the intersection.

What is the use of private set in C#?

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must: declare fields/variables as private. provide public get and set methods, through properties, to access and update the value of a private field.

What is private set Swift?

However, the access level for the numberOfEdits property is marked with a private(set) modifier to indicate that the property's getter still has the default access level of internal, but the property is settable only from within code that's part of the TrackedString structure.


1 Answers

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; }
}
like image 173
Mark Byers Avatar answered Oct 05 '22 09:10

Mark Byers