Are There Any Reasons to Use Private Properties in C#

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

I use them if I need to cache a value and want to lazy load it.

private string _password;
private string Password
{
get
{
if (_password == null)
{
_password = CallExpensiveOperation();
}

return _password;
}
}

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

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.

Why use private members then use public properties to set them?

In general, the point is to separate implementation (the field) from API (the property).

Later on you can, should you wish, put logic, logging etc in the property without breaking either source or binary compatibility - but more importantly you're saying what your type is willing to do, rather than how it's going to do it.

I have an article giving more benefits of using properties instead of public fields.

In C# 3 you can make all of this a lot simpler with automatically implemented properties:

public class Foo
{
public string[] WorkID { get; private set; }
}

At that point you still have a public getter and a private setter, but the backing field (and property implementation) is generated for you behind the scenes. At any point you can change this to a "normal" fully-implemented property with a backing field, and you'll still have binary and source compatibility. (Compatibility of serialized objects is a different matter, mind you.)

Additionally, in this case you can't mirror the behaviour you want (the ability to read the value publicly but write it privately) with a field - you could have a readonly field, but then you could only write to it within the constructor. Personally I wish there were a similar shorthand for this:

public class Foo
{
private readonly int id;
public int Id { get { return id; } }

...
}

as I like immutable types, but that's a different matter.

In another different matter, it's generally not a good idea to expose arrays like this anyway - even though callers can't change which array WorkID refers to, they can change the contents of the array, which is probably not what you want.

In the example you've given you could get away without the property setter, just setting the field directly within the same class, but it would mean that if you ever wanted to add logging etc you'd have to find all those writes.

Difference between private properties and private fields

The two code samples you gave are functionally equivalent right now, but the main reason for getter / setter methods (whether they're in the form of "properties" or explicit methods) is that their implementation can be changed without modifying the code that calls them. If you did that, these would not be equivalent, because the first one doesn't actually call the setter and the second one does. To match the second, the first constructor should be written as follows:

public test()
{
setTesting(false);
}

Or the second should be written to not call the setter, i.e. set the field instead of the property:

public test()
{
_isTesting = false;
}

private bool _isTesting;

public bool isTesting {
private set { _isTesting = value; }
get { return _isTesting; }
}

Other than that, there is no practical difference -- in most cases: Even though properties are essentially compiled into getter and setter methods anyway, they still retain metadata that they are in fact "properties" as opposed to "methods", and some APIs rely on this information.

The other difference is semantics: Properties are meant to be treated as if they are fields, implying that they do some kind of basic storage / retrieval from memory. If I see a method named GetX as opposed to property X in C# code, I'll probably assume that the method is doing something more advanced and treat it differently.

Is there any benefit to declaring a private property with a getter and setter?

Private properties provide you a level of abstraction when you assign the value to the private variable (which is created for you by the compiler). It's not less efficient to do so, and if you need to change how the assignment is done in the future, you only have to worry about updating it in one place.

It can also provide consistency in an application. If all assignments are done through properties, then some can validate the assignment values while others not. To the person interfacing with the property, there is no difference between those which validate and those which do not. (and this way someone doesn't accidentally assign a value to a local variable which doesn't validate.)

Should I use private fields in my C# class or public Properties are good enough?

The answer here will really depend on whether you want the first/last name to be on the public API. If you do: 2 is ideal for your typing convenience. At runtime, thanks to JIT magic, 1 and 2 will be largely indistinguishable (except for the accessibility concern), so you might as well go with the most convenient and expressive form, which is usually: 2.

Even 1 could use private automatically implemented properties if you so wish, although it is pretty rare to see that in reality - most code either uses public properties or private fields, depending on the intent; public fields are anecdotally rare, as are private properties.

It might also make sense to have the first and last names public but read-only, i.e.

public string FirstName { get; }
public string LastName { get; }

public string FullName => FirstName + LastName;

or public but only writable inside the type:

public string FirstName { get; private set; }
public string LastName { get; private set; }

public string FullName => FirstName + LastName;

Fields vs Properties for private class variables

For a private member, I only make it a property when getting and/or setting the value should cause something else to occur, like:

private int Limit
{
get
{
EnsureValue();
return this._limit;
}
}

Otherwise, fields are fine. If you need to increase their accessibility, it's already a big enough change that making it a property at that point isn't a huge deal.

Edit: as Scott reminds us in the comments, side effects in properties can often cause more pain than anything else. Don't violate Single Responsibility and limit property logic to consistent, logical operations on the value only that must be done at the gate - such as lazy loading (as in the example above), transforming an internal structure into a publicly-useful format, etc.

What is the benefit of using a private member in a get instead of just having the class auto set the property itself?

public int SomeValue
{
get { return _someValue; }
}
private int _someValue;

is not the equivalent of

public int SomeValue { get; }

If you do the auto property it is equivalent to

public int SomeValue
{
get { return _someValue; }
}
private readonly int _someValue;

You can not change the value of _someValue internally with the auto property but you could with the original code.

That being said, based on your comments, the code was most likely written before C# 6 when auto read only properties where introduced and the original author was too lazy or did not know that he could mark _someValue as readonly and did not intend for _someValue to be changed anyway.

Why should I use a private variable in a property accessor?

Your examples are semantically the same. The concise property declaration syntax (just having { get; set; }) is a shortcut available in C# 3.0. The compiler actually creates a private backing variable and a simple getter and setter as in your first example.

If all you're doing is creating a getter and setter (and nothing actually happens when either occurs), then the concise syntax is a good option. If you have to perform any other actions (redraw a control, for example) when you set the value, then the full syntax is required.



Related Topics



Leave a reply



Submit