Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design this using OOP

Tags:

c#

oop

I have an object called User, with properties like Username, Age, Password email etc.

I initialize this object in my ado.net code like:

private User LoadUser(SqlDataReader reader)
{
      User user = new User();

      user.ID = (int)reader["userID"];
      // etc
}

Now say I create a new object that inherits from User, like:

public class UserProfile : User
{
     public string Url {get;set;}
}

Now I need to create a method that will load the userprofile, so currently I am doing:

public UserProfile LoadUserProfile(SqlDataReader reader)
{
         UserProfile profile = new UserProfile();

         profile.ID = (int)reader["userID"];
         // etc. copying the same code from LoadUser(..)
         profile.Url = (string) reader["url"];
}

Is there a more OOP approach to this so I don't have to mirror my code in LoadUserProfile() from LoadUser()?

I wish I could do this:

UserProfile profile = new UserProfile();

profile = LoadUser(reader);

// and then init my profile related properties

Can something like this be done?

like image 302
mrblah Avatar asked Jun 04 '26 20:06

mrblah


1 Answers

Move the LodUser method to the User Base class and make it virtual. Then, in the UserProfile method, you override this method.

public class User
{
   public virtual void Load(SqlDataReader reader)
   {
      this.Id = reader["Id"];
      //.. whatever else
   }
}

public class UserProfile : User
{
   public string ExtraProp {get;set;}
   public override void Load(SqlDataReader reader)
   {
      base.Load(reader);
      this.ExtraProp = reader["ExtraProp"];
   }
}

Then you can just do something like:

UserProfile up = new UserProfile();
up.Load(myReader);
like image 70
BFree Avatar answered Jun 07 '26 10:06

BFree