Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# private properties - are they used/make sense?

I'm starting out as a C# enthusiast and it seems to me that properties should always be public. Private property wouldn't make sense. Would it?

Would this:

private string propertyOne {get; set;}

be equivalent to this:

public string propertyOne {private get; private set;}
like image 824
s5s Avatar asked Dec 04 '22 06:12

s5s


2 Answers

Yes, private properties can make sense, particularly in cases where you have logic you want to implement in the getters/setters. You may only want these accessible within the class (hence they're private) but you still want to encapsulate the getter/setter logic in one place.

There is a difference between the two lines of code you printed. Someone reflecting over public properties won't see the first one but they will see the second, even if they can't invoke the getter/setter.

like image 83
triangle_man Avatar answered Dec 12 '22 09:12

triangle_man


The idea of using a Property is to encapsulate rather than just present a raw variable to the 'outside world'. That way you can also have an extra logic in your accessors.

So No, a purely private property wouldn't be the usual use case.

It's not uncommon to see public properties with a private setter though.

like image 32
Mitch Wheat Avatar answered Dec 12 '22 11:12

Mitch Wheat