Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# base inheritance

This issue has been on/off bugging me and I've written 4 wrappers now. I'm certain I'm doing it wrong and need to figure out where my understanding is branching off.

Let's say I'm using the Rectangle class to represent bars of metal. (this works better then animals)

So say the base class is called "Bar".

private class Bar
{
   internal Rectangle Area;
}

So. Now we make a rectangle, say 300 units by 10 units.

private Bar CreateBar()
{
    Bar1 = new Bar1();
    Bar1.Area = new Rectangle(new Point(0,0), new Size(300,10));
    return Bar1;
}

Fantastic, so we have a base bar.

Now let's say we want to make this bar have a material - say steel. So. . .

private class SteelBar : Bar
{
    string Material;
}

So if I did this. . .

private SteelBar CreateSteelBar()
{
    SteelBar SteelB = new SteelB();
    Bar B = CreateBar();
    SteelB = B;
    SteelB.Material = "Steel";
    return SteelB;
}

From what I get from this if I call CreateSteelBar, it creates a steelbar that calls CreateBar. So I end up with a steel bar with a 300 by 10 rectangle, and a nulled or empty string for material. Then I set the material to steel.

When I try something similar in my program, it keeps telling I cannot implicitly create a higher up class from a lower down class. I would have figured this is why inheritance exists considering all the inherits from animal examples I see, but am hoping someone can clear me up.

Also, I'm certain I could call SteelBar = CreateBar(); but I did it the long way here.

like image 211
Charles Avatar asked Jun 13 '12 17:06

Charles


1 Answers

Instead of having a method (CreateBar), you'd use a constructor:

public Bar()
{
    this.Area = new Rectangle(new Point(0,0), new Size(300,10));
}

Then, in SteelBar, you'd call the base class constructor:

public SteelBar()
{
    this.Material = "Steel";
}

The base class constructor will occur first, so your area will already be setup. You can be explicit about this, though, and show it in your code:

public SteelBar()
    : base()
{
    this.Material = "Steel";
}

However, this is typically only used if you want to have a specific constructor that takes arguments.

For details, see Constructors in the C# programming guide.

like image 124
Reed Copsey Avatar answered Nov 14 '22 23:11

Reed Copsey