I'm currently reading trough a C# tutorial. Now I came across this:
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class Tabletop : Rectangle {
private double cost;
public Tabletop(double l, double w) : base(l, w) { }
public double GetCost() {
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display() {
base.Display();
Console.WriteLine("Cost: {0}", GetCost());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Tabletop t = new Tabletop(4.5, 7.5);
t.Display();
Console.ReadLine();
}
}
}
In the class Tabletop
there is cost
declared twice. Once as private double cost;
and 4 lines later as double cost;
Why is that so?
When removing double cost;
the Code still works. When double cost
is in the code I can hover over private double cost;
and read the message: The field Tabletop.cost
is never used". I pretty much can remove either of the cost and the code works fine.
- Did they forget to remove one of the declareation or is there a reason behind?
- Also, why don't I get an error message like "cost is already defined"?
Here is the Tutorial link
private double cost;
is unused and can be removed.
You don't get an error because as John said in the comments, it's in different scopes; one is defined as a field of the class while the other is a local variable. When cost
is used, the local variable is accessed. To access the field, this.cost
can be used.
class A
{
private int a = 1;
void A()
{
int a = 2;
Console.WriteLine(a); // 2
Console.WriteLine(this.a); // 1
}
}
Note you cannot have multiple local variables with the same name, even in different scopes:
void A()
{
int a = 1;
if(someCondition)
{
int b = 2; // Compiler error: A local variable named 'a' cannot be declared in this scope because it would give a different meaning to 'a', which is already used in a 'parent or current' scope to denote something else
}
}