Please can someone explain what the difference is, if any?
There isn't any difference between:
public string GetTitle()
{
return title;
}
and this:
public string GetTitle()
{
return this.title;
}
The this
refers to the instance of the class. So you can access the field either as title
or as this.title
.
However, I don't see any in following the above approach for defining a getter and a setter. Instead of following the above approach, you could use the following syntax, in order to achieved the same thing:
public string Title { get; set; }
and whenever you want to read the Title
, you just use the following
classInstance.Title
and whenver you want to set it's value, you just use the following:
classInstance.Title = "your title";
In both cases classInstance
as it's name implies is a n instance of your class.
It is remarkable to state here that the above is called auto-implemented properties. Before this, the only way you could do the same, it would be the following:
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
The following syntax is used nowadays, whenever you want to apply any logic inside the get
or set
. If it isn't this the case, then the auto-implemented property approach is usually followed, since it is more compact.