Re: C# Properties Question
The properties are only available to instances of objects. So let's extend the code a bit.
Code:
public class Car
{
private string color;
public string Color
{
get
{
return color.ToUpper();
}
set
{
if(value == "Red")
color = value;
else
Console.WriteLine("This car can only be red!");
}
}
}
Code:
Car myNewCar = new Car();
myNewCar.Color = "Red"; // This sets the value of the color property to red.
myNewCar.Color = "Blue"; //This displays the warning message on the console.
Console.WriteLine(myNewCar.Color); // Displays "RED" on the console.
The easiest way to explain would be, Properties allow you to get or set values for an object. They are for use in Assignment operations. You Set the color of the car, or you Get the color of the car. The Setting or Getting is determined by the type of assignment operation. IE.
myNewCar.Color = "Red";
will call the SET portion.
The statment...
string CarColor = myNewCar.Color;
Will call the get portion.
Methods are more for Actions. Car.Start(); would be a method.
This is a very simplistic description.
The variable value is always implied on the "Set" property;
Re: C# Properties Question
So value is the default variable that is passed to the method? That makes sense, since I don't see it declared anywhere else.
Re: C# Properties Question
A couple of things:
1) check out using auto-properties (no need to have a separate private variable with an auto-property)
2) check out using enums (storing such a value as a string isn't very efficient, nor are each value typesafe).
Code:
public enum CarColor { Red, Green, Blue };
public class Car
{
// Auto-property (with a private setter)
public CarColor Color { get; private set; }
// ctor
public Car( CarColor color )
{
Color = color; // sets the initial color
}
}
Usage:
Code:
var car = new Car( CarColor.Red);
Console.WriteLine( car.Color ); // prints Red
car.Color = CarColor.Blue; // compiler error - can't set the private setter from here