First, I think you're asking many questions, not one.
And half of the answers of these questions is the ever correct "It depends".
In general, exposing object ivars directly is discouraged if you're aiming for looser coupling (obviously). Although I think when it comes to IBOutlets it is an acceptable practice, since after all the Interface Builder is tasked with the creation of the object.
On the other hand, a readwrite property for an NSInteger
makes little sense, unless you're doing something very funky, and you can easily use an ivar instead.
Once upon a time, in pre-ARC ages, there were some people, who advocated always using properties for objects, since then you don't need to care about retain
/release
. However now that ARC is widely used, this makes almost no difference and it is mostly a cosmetical thing.
A final piece of advice: aim for consistency project-wide.
EDIT: I'm not the greatest fan imaginable of Design Patterns, but it seems that most of your questions would find the best answer in this book.
The C# team has considered that this would be a very useful feature, and that's why in C# 6, they implemented it (just a little different from your proposal).
Getter-only auto-properties
This new kind of properties are getter-only, but can be set either inline or in the constructor. This means they are backed internally by a readonly field.
Instead of declaring a property as readonly set
, you simply not declare it.
Inline assignment
public class Customer
{
public string First { get; } = "Jane";
public string Last { get; } = "Doe";
}
Constructor assignment
public class Customer
{
public string Name { get; }
public Customer(string first, string last)
{
Name = first + " " + last;
}
}
You can read about this and other new features of C# 6 in the Roslyn wiki in GitHub.
Best Answer
If you take a look here, you'll see that the following code:
Is lowered by the compiler to:
and the property gets further lowered to a
get_layouts1()
method.In other words, auto-property initializers are pure syntactic sugar. They provide a means of using auto-properties, whilst still allowing the backing field to be initialised.
So from a mutability point of view, there's no difference between them at all. Both provide read-only access to a list that is initialised when an instance of the class is created.
It's possible that it creates a slight performance overhead as the method must be called to obtain the list reference, but it's likely that the CLR JIT optimises the method away and just accesses the field directly.
The most obvious use for private properties is for lazy loading/deferred execution purposes. There are other uses, but as a guideline, they are often pointless "noise". I'd not go so far as to say that using a private property is worse than just using a field, but I'd advise just using a read-only field for most cases.