clarication of tutorial code

Reply Forum
Forum postFraz @ 2009-07-02 18:37:09
ReplyReply to
Hi, i was wondering if someone would be kind enough to read over this code i have copied from the tutorial and check to make sure that the things i have listed in comments are correct + clarify where i have placed a "?".

thanks very much in advance

Rgds

Fraz



using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args) //program begins here
{
Car car;
//creating an object called car from Car class

car = new Car("Red"); //declaring its colour red
Console.WriteLine(car.Describe());

car = new Car("Green"); // declaring it green
Console.WriteLine(car.Describe());

Console.ReadLine(); //allows user to c writeline

}
}

class Car
{
private string color;

//settin up a private variable of type string

public Car(string color) // a method?
{
this.color = color; //?
}

public string Describe() // describe method?
{
return "This car is " + Color; //?
}

public string Color

// is this where the colour is set?
{
get { return color; }
set { color = value; }
}
}
}


Forum postWebmaster @ 2009-07-03 11:04:25
ReplyReply to
Hi Fraz,

Here is a bit of feedback on your code. Your code/question first, then my reply. Good luck :)

>Car car; //creating an object called car from Car class

Actually, you are merely declaring it here.

>car = new Car("Red"); //declaring its colour red

Not exactly. You instantiate the object which you declared above, and passing a value to it's constructor. The result is the same though :)

>public Car(string color) // a method?

Yes, but a special method, called a constructor. This is the only kind of method in C# that doesn't force you to declare a return type, since a constructor will never return anything. More on constructors here.

>this.color = color; //?

The "this" keyword refers to the instance of the class that it's used within. In this case, you assign the color parameter to the private variable "color".

>public string Describe() // describe method?

Just a custom, user method. Nothing strange there :)

>return "This car is " + Color; //?

You access the public Color property. You could write this.Color instead, to be more specific, or you could simply use the private color member, since you are within the class and therefore have access to private members :)

>// is this where the colour is set?

Yes, sort of. It's a public property, meant as a gateway to your private variable. More on properties here.


I hope this helps :)











© net-tutorials.com 2006 - 2012

MailContact net-tutorials.com