Generics and inheritance

Generics and inheritance

am 19.11.2007 13:18:01 von billr

Sorry if this is the wrong group, but I cna think not of where else to post.

I have an inheritance hierarchy in place as follows ...

PersonVisitor <-- AlphabeticVisitor <-- FamilyNameVisitor

public interface IPerson
{
string GivenName { get; set; }
string FamilyName { get; set; }
IPerson Clone();
void Visit(PersonVisitor visitor);
}

public abstract class PersonVisitor where T : IPerson
{
virtual public void Visit(T c) { }
}

public abstract class AlphabeticVisitor : PersonVisitor where T :
IPerson
{
// class code omited
}

public class FamilyNameVisitor : AlphabeticVisitor where T : IPerson
{
override public void Visit(T c)
{
}
}

Firstly, I would expect that I could pass an object of type
FamilyNameVisitor as follows

Customer c = PeopleFactory.CreateNewCustomer("Marcus", "Barnard");
Assert.IsNotNull(c, "Failed to instantiate the Customer object");
FamilyNameVisitor v = new FamilyNameVisitor();
c.Visit(v);

However, I am told that this is not possible because an object of type
FamilyNameVisitor cannot be converted to type
PersonVisitor (even though FamilyNameVisitor is a
sub-class of PersonVisitor, AND Customer is a sub-class of IPerson)

So, I then put the following implicit conversion into the FamilyNameVisitor
class definition

public static implicit operator
PersonVisitor(FamilyNameVisitor v)
{
return (v as PersonVisitor);
}

but this conversion always returns null :o(

Can somebody please help?

Thanks in advance

--
Of all words of tongue and pen, the saddest are: "It might have been"

Bill.Richards @ greyskin .co .uk
http://greyskin.co.uk

Re: Generics and inheritance

am 19.11.2007 22:38:20 von mattias.dont.want.spam

>However, I am told that this is not possible because an object of type
>FamilyNameVisitor cannot be converted to type
>PersonVisitor (even though FamilyNameVisitor is a
>sub-class of PersonVisitor, AND Customer is a sub-class of IPerson)

FamilyNameVisitor is *not* a subclass of
PersonVisitor. In your case I think the easiest solution is
to make the Visit method generic as well

void Visit(PersonVisitor visitor) where T : IPerson


Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.