Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Member variable inheritance

I'm a little new to C#, but I have a fairly extensive background in programming.

What I'm trying to do: Define different MapTiles for a game. I've defined the base MapTile class like this:

public class MapTile
{
    public Texture2D texture;
    public Rectangle mapRectangle;

    public MapTile(Rectangle rectangle)
    {
        this.mapRectangle = rectangle;
    }
}

I then define a subclass GrassTile like this:

class GrassTile : MapTile
{
    new Texture2D texture = Main.GrassTileTexture;
    new public Rectangle mapRectangle;

    public GrassTile(Rectangle rectangle) : base(rectangle)
    {
        this.mapRectangle = rectangle;
    }
}

In my Main class I'm creating a new maptile like this:

Maptile testTile;
testTile = new GrassTile(new Rectangle(0, 0, 50, 50);

However, when I try to render this testTile, its texture ends up being null. My code works fine if I define the texture inside MapTile, so it has nothing to do with my previous implementation of it.

So how can I get GrassTile to be able to modify MapTile's member variable texture? or get my main class to recognize GrassTile's texture instead of MapTile's I fiddled with interfaces as well, but I can't declare interface member variables. Is there something else to C# inheritance that I don't get yet?

Thanks in advance

like image 304
Logicon211 Avatar asked Jan 16 '13 22:01

Logicon211


2 Answers

Child class will inherit members of parent class. You don't need to specify them. Also it's better to use properties rather than public fields.

public class MapTile
{
    public Texture2D Texture { get; set; }
    public Rectangle MapRectangle { get; set; }

    public MapTile(Rectangle rectangle)
    {
        MapRectangle = rectangle;
    }
}

public class GrassTile : MapTile
{    
    public GrassTile(Rectangle rectangle) : base(rectangle)
    {
        Texture = Main.GrassTileTexture;
    }
}
like image 105
Sergey Berezovskiy Avatar answered Nov 14 '22 20:11

Sergey Berezovskiy


You have a little bit of a syntax confusion. "new" keyword can either be used as an operator to instantiate something, as you do in your main, or as a modifier to members to hide inherited members and that's what you're doing in your GrassTile. You're essentially redefining your members there. Correct version might be:

   class GrassTile : MapTile
    {
        public GrassTile(Rectangle rectangle) : base(rectangle)
        {
            texture = Main.GrassTileTexture;
        }
    }

as your rectangle gets set in the base constructor anyway.

like image 2
canahari Avatar answered Nov 14 '22 18:11

canahari