Should fields be public or private?

Should fields be public or private?

Fields should be declared private unless there is a good reason for not doing so. One of the guiding principles of lasting value in programming is “Minimize ripple effects by keeping secrets.” When a field is private , the caller cannot usually get inappropriate direct access to the field.

Can properties be private?

Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property. For more information, see Static Classes and Static Class Members.

Should I use properties C#?

In general you should use properties if you need them to look and behave like a variable. Properties give you a level of abstraction so you can change the fields while not affecting how they’re used by a class.

Should I use this in C#?

If you want to distinguish > between local and member variables you should use “this.” in C# and “Me.” in VB.NET.

Are public fields bad?

In general, yes, using public fields instead of properties is a bad practice. You can use them as part of an interface definition or an abstract class.

Why is private field marked private in properties?

The real location of a property’s data is often referred to as the property’s “backing store.” It is common for properties to use private fields as a backing store. The field is marked private in order to make sure that it can only be changed by calling the property.

When to use a property instead of a field in C #?

In almost all cases, fields should be private. Not just non-public, but private. With automatic properties in C# 3, there’s basically no cost in readability or the amount of code involved to use a property instead of a field.

Are there any reasons to use private properties in C #?

Using a property, even a private one, does help future-proof your code so that you can add the logic to a getter later, if required. If I feel that a property may eventually require extra logic, I will sometimes wrap it into a private property instead of using a field, just so I don’t have to change my code later.

What’s the difference between private and public fields in C #?

With automatic properties in C# 3.0, I rarely see a need to implement fields directly — private or public. The big gain you can get from a property (private, public.) is that it can produce a calculated value vs. a set value. For example