views:

91

answers:

3

I have the following class with static properties and methods which helps manage users on a website. I want to be able to re-use this class among other projects by overriding some properties.

public class Account {

    public static string sessionName = "Account";
    public static string tableName = "Accounts";

    public static bool isLoggedIn(){

        return HttpContext.Current.Session[sessionName] != null;

    }

    public static bool login(string email, string password){

        //connect to database and return user details from specified table
        DataTable t = Database.login(tableName, email, password);

        DataRow r = t.Rows[0];

        HttpContext.Current.Session[sessionName] = r;

        return true;

    }

    public static object val(string name){

        return ((DataRow)HttpContext.Current.Session[sessionName])[name];

    }

}

This basically logs a user in and stores their details in a DataRow in the session, using a session name defined in the properties.

Is it possible to do something like below to use this class with multiple types of user?

public class WebsiteUser : Account {

    public override string sessionName = "WebsiteUser";
    public override string tableName = "WebsiteUsers";

}

public class TradeUser : Account {

    public override string sessionName = "TradeUser";
    public override string tableName = "TradeUsers";

}

Then call the following code to use each derived class.

if (WebsiteUser.isLoggedIn()){

    //manage website user

}

if (TradeUser.isLoggedIn()){

    //manage trade user

}
+6  A: 

No. You can not override static members.

Your idea is good. Just Refactor the code to use instance members and override them.

Or better yet, int his specific case - pass the values as constructor arguments. You are not overriding any logic, you just need to store and return data in fields.

Marek
A: 

You are confusing concepts: you can override methods, not attributes. Just make a constructor that takes initialization values for the attributes and initializes them accordingly. Besides, that only makes sense if the whole static stuff in gone.

A: 

I would:

  • Make sessionName and tableName non-static instance members, initialized in the Account constructor
  • Create several static instances of the Account class, named e.g. websiteUser and tradeUser
  • Construct these instances using different sessionName and tableName
  • Don't have sublasses of the Account class

Instead of if (WebsiteUser.isLoggedIn()), the code would look like if (Account.websiteUser.isLoggedIn().

ChrisW