C# Member variable inheritance

c#, inheritance, member-variables, variables

Solution

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;
    }
}

Problem

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

Original source

Related problems