Skip to content
Advertisement

Is there a way to access a field/variable of a child class from the base class? Does it even make sense?

(I am kind of new to C# so please forgive me if my question makes anyone laugh 🙂 ). I have a ‘database’ class which has a method public bool Create(). And ‘user’ class which has a field string table_name = "user_table" and it inherits the ‘database’ class. Is there a way to access user.table_name from the ‘create’ method of ‘database’ class? I am coming from php where you can use the keyword static::$variable_name from base class and it returns the value of that variable which is in the child class. For example:

    class A{
        public static function func(){
            $a = static::$variable_in_child_class; // calling the variable that is in child class
            print $a;
        }
    }

    class B extends A{
        public static $variable_in_child_class= "some value"; // variable in B class
    }

    $b = new B(); // object of type B
    $b->func();   // prints "some value"

Can i do anything similar in c#? Like:

    class database{
        public bool Create(){
            string table_name = //get the table name from child class
        }        
    }

    class user : database{
        public string table_name = "user_table";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        user u = new user();
        u.create(); // calls create method from base without passing any argument
    }

Advertisement

Answer

I think the best solution is to implement constructors for your classes:

class database
{
    public database()
    {
        //Parameterless constructor, should you need it.
    }
    public database(string table_name)
    {
        var tablename = table_name; //Initialization logic goes here
    }
}

Then your user class can call the base constructor as such:

class user: database
{
    public static string table_name = "user_table";

    public user() : base(table_name) { }

}

Which in turn gives the desired result:

private void button1_Click(object sender, EventArgs e)
    {
        user u = new user();
        u.create(); // calls create method from base without passing any argument
    }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement