patterncsharpCritical
Public Fields versus Automatic Properties
Viewed 0 times
publicversuspropertiesautomaticfields
Problem
We're often told we should protect encapsulation by making getter and setter methods (properties in C#) for class fields, instead of exposing the fields to the outside world.
But there are many times when a field is just there to hold a value and doesn't require any computation to get or set. For these we would all do this number:
Well, I have a confession, I couldn't bear writing all that (really, it wasn't having to write it, it was having to look at it), so I went rogue and used public fields.
Then along comes C# 3.0 and I see they added automatic properties:
Which is tidier, and I'm thankful for it, but really, what's so different than just making a public field?
But there are many times when a field is just there to hold a value and doesn't require any computation to get or set. For these we would all do this number:
public class Book
{
private string _title;
public string Title
{
get => _title;
set => _title = value;
}
}Well, I have a confession, I couldn't bear writing all that (really, it wasn't having to write it, it was having to look at it), so I went rogue and used public fields.
Then along comes C# 3.0 and I see they added automatic properties:
public class Book
{
public string Title { get; set; }
}Which is tidier, and I'm thankful for it, but really, what's so different than just making a public field?
public class Book
{
public string Title;
}Solution
In a related question I had some time ago, there was a link to a posting on Jeff's blog, explaining some differences.
Properties vs. Public Variables
-
Changing a variable to a property is a breaking change. For example:
Properties vs. Public Variables
- Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
- You can't databind against a variable.
-
Changing a variable to a property is a breaking change. For example:
TryGetTitle(out book.Title); // requires a variableCode Snippets
TryGetTitle(out book.Title); // requires a variableContext
Stack Overflow Q#1180860, score: 201
Revisions (0)
No revisions yet.