The Concrete Hidden Property Pattern

May 5, 2014 - Programming

In a project I’ve been working on recently, I’ve gone a bit overboard on generics. As such I’ve come up with a couple of patterns to help me out – these probably already exist but I don’t know the names for them.

Say we have a property Animal of type IAnimal in my base class

public abstract class Cage 
{ 
    public IAnimal Animal { get; set; } 
}

and I have a derived class where I want the following (where Bird implements IAnimal)

public class BirdCage : Cage 
{ 
    // hide base.Animal 
    public new Bird Animal { get; set; } 
}

then I’m a little stuffed when it comes to doing something like so:

var birdCage = new BirdCage { Animal = new Bird(); } 
var tigerCage = new TigerCage { Animal = new Tiger(); } 
var cages = new List { birdCage, tigerCage } 
Assert.IsNotNull(cages[0].Animal); // bad times

the above Assert will fail because birdCage is being treated as it’s parent Cage to which you have not assigned the Animal property.

So how do we get round this? With generics.

We create a new class to act as a intermediate between the base Cage and our concrete implementations

public abstract class Cage<TAnimal> : Cage 
    where TAnimal : IAnimal 
{ 
    public new TAnimal Animal 
    { 
        get { return (TAnimal)base.Animal; } 
        set { base.Animal = value; } 
    } 
}

then our concrete class simply becomes

public class BirdCage : Cage<Bird> { }

now the above test will pass because we are assigning and retrieving the value from the base class.

› tags: c# /