Jump to content

Polymorphism of Member Variables?


DooVoo
 Share

Recommended Posts

Hi All,It's been a while since I last posted here. I've come across a small issue with my latest project, a registration and login system. This will then also have a seperate login system for administrators.To try and keep the amount of duplicated code to a minimum I've created a User class which the Login:Page class accesses and then created the derived classes AdminUser and AdminLogin which inherit the properties of User and Login respectively.My problem is this. The Login class uses a User instance called mUser, but the AdminLogin class needs to use an instance of AdminUser, also called mUser to avoid having to rewrite the inheritted code. Below is a stripped down version of the problem.

public class User {    public virtual void DoSomething() {        // Do Something.    }}public class AdminUser:User {    public override void DoSomething() {        // Do Something Else.    }}public class Login:Page {    private User mUser;    public Login() {        mUser = new User();        mUser.DoSomething();    }}public class AdminLogin:Login {    public AdminLogin() {         // Something to turn mUser into an AdminUser datatype.    }}

I believe that the data type of mUser could be set at runtime by using the base Object class and then using boxing and unboxing to assign it, but I can't quite figure it out. Below is an example, it doesn't work but it might give someone some inspiration!

// Using the same User and AdminUser examples above.public class Login:Page {    private User mUserRef;    protected Object mUser;    public Login() {        mUserRef = new User();        mUser = mUserRef;         // Boxing mUserRef into mUser.        mUser.DoSomething();    }}public class AdminLogin:Login {    private AdminUser mAdminUserRef;    public AdminLogin() {        mAdminUserRef = new AdminUser();        mUser = mAdminUserRef;     // Boxing mAdminUserRef into base.mUser.        mUser.DoSomething();    }}

I hope someone can help me with this, it's incredibly fustrating!NB: I realise a single login system with userlevels would work, but i want a coded solution to help me understand more about c# - I'm being difficult I know, but it's the only way I'll learn :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...