One of the better things built into this language are properties. Generally speaking, they are (usually) public
members of a class that (typically) provide an easy way to read/write to attributes and (sometimes) compute
something of interest (say, the
Area of a
Shape or the
Probability I will love whatever movie Karen Gillian stars in
The answer is
always 107%.). These are not to be confused with attributes or data members (although the convention is to
name the property after the attribute, capitalizing the first letter), which means that these cannot be used as
ref or
out arguments.
Let's look at the most common implementation of a property:
public class Slacker
{
private int alpha; // This is my private attribute
public int Alpha // This is my public property
{
get { return alpha; } // The attribute
set { alpha = value; } // "value" is the default name to the assignment operand
}
}
This will allow me to read/write the
alpha attribute of my
Slacker objects, by simply referring to the
Alpha property. Such as,
myObject.Alpha = 100;. As opposed to something like
myObject.setAlpha(100);
[You]: This seems like a fairly contrived use of a property... I mean, I could just declare the
attribute as public if there's no code that objects to how the value is modified!
[Me]: You're right but also, this is an
example I'm writing out
in HTML, which
is annoying to format. So cut me some slack here!
You might find a use in specifying the
set portion of any given property as
private in order to only allow methods of that class to modify the corresponding
attribute value. Such as
public int Alpha { get; private set; }, which is a simpler
implementation of what's listed in the above example.
[You]: Okay, but the methods of a class already have access to the private attributes...
That's also a good point, which I'm going to ignore and instead talk about another trick you can use. That is
to define a
get-only property that is defined by an expression instead of a single
attribute value, like you might do if you have individual attributes for your first and last names, or the
Department code and number of a class you're enrolled into.
public string Name => Last + ", " + First;
public string CourseListing => Dept + " " + Number;