Inheritence with Generics

written by Ryan Olshan on Friday, March 03 2006

I answered a post on the ASP.NET forums where somebody was having problems with Generics and class inheritence. I ended up cooking this up as an example based upon what they had already provided in the thread.

using System;

using System.Collections.Generic;

 

public abstract class BaseClass { }

public class ClassA : BaseClass { }

public class ClassB : ClassA { }

public class GenericClass<SomeType> : ClassB { }

 

public class NonInheritingClass<T> where T : BaseClass

{

   private List<GenericClass<T>> m_list;

 

   public virtual int AddToList(GenericClass<T> baseObject)

   {

      if (this.m_list == null)

      {

        this.m_list = new List<GenericClass<T>>();

      }

 

      this.m_list.Add(baseObject);

 

      return m_list.Count;

   }

}

 

public class SomeClass

{

   public static int TestMethod()

   {

      int count;

 

      NonInheritingClass<ClassB> nonInheritingClass = new NonInheritingClass<ClassB>();

      GenericClass<ClassB> classB = new GenericClass<ClassB>();

 

      count = nonInheritingClass.AddToList(classB);

 

      return count;

   }

}

Kick this post on .NET Kicks

Similar Posts

  1. Creating a List of a custom class
  2. Nullable type to string function
  3. Strong Coders Generic Data Access Library

Post a comment