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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With