Search code examples
c#thistypeofequals-operator

C# this.Equals(typeof(...));


I have following piece of code:

class Tile
{
    public TCODColor color { get; protected set; }
    public int glyph { get; protected set; }

    public Boolean isDigable()
    {
        return this.Equals(typeof(Wall));
    }
    public Boolean isGround()
    {
        return this.Equals(typeof(Floor));
    }
}

The Wall and Floor class both inherit from Tile. At another point in the program I have a if-statement which goes like this for example:

public void dig(int x, int y)
{
    if (tiles[x, y].isDigable())
    {
        tiles[x,y] = new Floor();
    }
}

The tiles are a two-dimensional array of the Tile class and the content of them gets initialized either as a Floor or Wall. So if the tile is a Wall it is Digable (and should return true) but no matter what it always returns false, thus, not executing other code. Since I am not familiar with C# I suppose I am doing something wrong Syntax-wise, any suggestions?


Solution

  • The Equals method is for testing if two values are equivalent (in some way), for example, to test if two variables of type Floor refer to the same instance in memory.

    To test if an object is of a certain type, use the is operator:

    public Boolean isDigable()
    {
        return this is Wall;
    }
    
    public Boolean isGround()
    {
        return this is Floor;
    }
    

    Or as Rotem suggests, you can modify your classes to make isDigable and isGround virtual methods and override them in your child classes, like this:

    class Tile
    {
        public TCODColor color { get; protected set; }
        public int glyph { get; protected set; }
    
        public virtual bool isDigable() 
        { 
            return false; 
        }
    
        public virtual bool isGround() 
        { 
            return false; 
        }
    }
    
    class Wall: Tile
    {
        public override bool isDigable()
        { 
            return true; 
        }
    }
    
    class Floor : Tile
    {
        public override bool isGround()
        { 
            return true; 
        }
    }