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:

JavaScript

Can i do anything similar in c#? Like:

JavaScript

Advertisement

Answer

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

JavaScript

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

JavaScript

Which in turn gives the desired result:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement