views:

140

answers:

4

I'm using an API that has a "Member" class. I wish to extend this so i have create "MemberProfile" which inherits from "Member"

I have some issue creating the constructor for this class. I wish to something like the following

    var member = Member.GetCurrentMember();
    var memberProfile = new MemberProfile(member);

How would the constructor on MemberProfile look. Do i need to do some kind of cast?

+10  A: 

I suggest adding a Member field to the MemberProfile class and initialize it in the constructor. Don't inherit from Member.

public class MemberProfile {
    public Member Member { get; private set; }
    public MemberProfile(Member member) { Member = member; }
}

If you really want to inherit from Member, you'll have to copy all the properties off the passed argument to the new instance manually.

Mehrdad Afshari
+1 for "Don't inherit from `Member`". It sounds like `MemberProfile` is not an extension of `Member`, but merely a class composed by it. In the mockup I was sketching I had `MemberProfile` as a property of `Member`; the inverse of your suggestion. I suppose either way could potentially work, depending on @frosty's needs.
JMD
@JMD: Indeed it does make sense (just based on the names) that `MemberProfile` becomes a property of `Member`, not the other way around but it seems to me from the question that `Member` is somethign you get from an existing API you don't have control on (or you don't want to modify) and need to extend it somehow.
Mehrdad Afshari
yeah it's an existing api, cool thanks guys good to get heads up
frosty
A: 

You would need to create a constructor which takes a Member as an argument and does a deep copy of the parameters.

public class MemberProfile : Member
{
    public MemberProfile(Member member)
    {
        base.field1 = member.field1;
        base.field2 = member.field2;
            .
            .
        base.fieldn = member.fieldn;
    }
}
Jeff Hornby
+2  A: 

Use the decorator pattern

+3  A: 

Mehrdad is correct; MemberProfile should not inherit from Member.

Making some assumptions about your application context, it seems likely that it is entirely plausible that at some point in the future one Member may have more than one Profile.

MemberProfile <<--uses--> Member

and not

MemberProfile --is-a--> Member
Steven A. Lowe