I've read the msdn.microsoft guides, a example of an acessor is the following:
// public class:
public class Tricycle
{
// protected method:
protected void Pedal() { }
// private field:
private int wheels = 3;
// protected internal property:
protected internal int Wheels
{
get { return wheels; }
}
}
It allows me to access the wheels variable in other classes trough Trycicle.Wheels, correct? But then there are properties, which need to be instantiated and seem to enable some accessing
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();
// Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = 24;
// Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine("Time in hours: " + t.Hours);
}
}
// Output: Time in hours: 24
In this example I have to instantiate a TimePeriod object, does this means I can't access the value of 'seconds' variable without instantiating? Why is there such difference between this example and the previous one? What makes it forcing me to instantiate?
I'm not very familiar with these concepts.
You should research static vs. instance members.
In this example:
public class Tricycle {
public static readonly int Wheels = 3;
public string Color {get; set;}
}
A property of all tricycles is that they have 3 wheels. Therefore, I made the Wheels
field static, and you can ask for Tricycle.Wheels
.
However, not every tricycle is the same color, so Color
is not static, and therefore you need a specific tricycle (an instance) in order to get or set its color.