0 Comments

Was strolling around StackOverflow and came to a question #1118232.  Where this guy was asking how come you can create a class inheriting from another generic class like so:

class Person : EntityBase<Person>
{
 //Whatever here...
}

He said it’s like the chicken and egg problem :)  Which I sort of agree.  After pondering on the thing for a bit, I tried mucking around with it in Visual Studio and came up with this that I think sort of give me a bit more clarification on the idea, but not by much… Still trying to find when I need to really use something like this.   And the code that I came up with is this:

class Program
    {
        static void Main(string[] args)
        {
            var wife = new Human(Gender.Female);
            var baby = wife.GiveBirth();
            Console.WriteLine(baby.Gender);
 
            Console.ReadKey();
        }
    }
 
    class CanGiveBirthTo<T> where T : new()
    {
        public CanGiveBirthTo()
        {
        }
 
        public T GiveBirth()
        {
            return new T();
        }
    }
   
    class Human : CanGiveBirthTo<Human>
    {
        public Gender Gender { get; private set; }
 
        public Human(Gender gender)
        {
            Gender = gender;
        }
 
        public Human()
        {
            Gender = RandomlyAssignAGender();
        }
 
        Gender RandomlyAssignAGender()
        {
            var rand = new Random();
            return (Gender) rand.Next(2);
        }
    }
 
    enum Gender
    {
        Male = 0,
        Female = 1
    }

I don’t know if this is of any use to anyone…, but enjoy… LoL.

Any idea what sort of real application code that could fall into this pattern in real project?