Generic types non-polymorphic?

Generic types non-polymorphic?

Old forum URL: forums.lhotka.net/forums/t/429.aspx


antoan posted on Wednesday, June 21, 2006

Hi,
I'm trying to understand a statement on p60 of the book regarding the reason BusnessBase inherits from non-generic BusnessBase:

"The primary reason for
pulling the functionality out of the generic class into a normal class is to enable polymorphism...It turns out that generic types are not polymorphic like normal types."

I am new to generics and trying to make sense of this.

I understand that you get a kind of compile time "polymorphism" behaviour if an inheriting normal type overrides generic base members without dynamic binding and Vtable infrastructure.

Antoan

RockfordLhotka replied on Wednesday, June 21, 2006

You can see it with any generic type. Try this:

List<int> numbers = new List<int>();

List<string> text = new List<string>();

Now write a method that can accept both numbers and text as parameters, like:

public void foo(List<> list)

You can't do it. In order to write foo() you need to fall back to a common, non-generic, base class or interface implemented by List<T> - which turns out to be IList in this case.

To resolve this limitation, BusinessBase<T> inherits from Core.BusinessBase, which is non-generic and thus is a common base class. In 2.0.1 I also added IEditableBusinessObject as a common (non-generic) base interface.

antoan replied on Wednesday, June 21, 2006

I get it now,

Really appreciate it Rocky, now I can continue through CH 2. : )

Cheers

FatPigeon replied on Monday, December 10, 2007

I am glad I found this thread as I was about to ask the same question. Surely generics are polymorphic as illustrated from the example below: Is not the reason that your example does not work that List<int> and List<Text> are unrelated types -eg one does not inherit from the other?

using System;
using System.Collections.Generic;
using System.Text;
using Csla;

namespace CslaTrial
{
    class BOTrial
    {
        void test()
        {
            A<int> a = new C();
            a.show();

            AP ap = new C();
            ap.show();
        }
    }

    public class AP
    {
        public virtual void show() { System.Windows.Forms.MessageBox.Show("AP"); }
    }

    public class A<T>: AP
    {
        public override void show() { System.Windows.Forms.MessageBox.Show("A"); }
    }

    public class B<T> : A<T>
    {
        public override void show() { System.Windows.Forms.MessageBox.Show("B"); }
    }

    public class C : B<int>
    {
        public override void show() { System.Windows.Forms.MessageBox.Show("C"); }
    }
}

Copyright (c) Marimer LLC