I have some rudimentary question about inheritance in C#.
I have two classes. I want the child class to inherit all members of the base class (e.g. x and y), but it seems to use inheritance I should initialize the base constructor. If I define another x and y in child class so that i later initialize the base constructor so what is the use of inheritance? And what is the solution?
The other question is that I have two methods with the same signature in base and child class and i need to use both. What can i do?
class Base
{
int x;
int y;
string name;
public Base(int i,int j)
{
x = i;
y = j;
name="s";
}
}
class Child
{
public Base()
{
}
}
Your questions are not very clear, and the code is invalid [now fixed by the editor] but I am going to answer what I think you are asking.
To initialize fields of a base class in a derived class, you must call the base constructor from the constructor of your derived class:
Now, regarding your second question regarding having a method in the derived class with the same name. If you wish to redefine the behaviour of a method, you should make it virtual in the base class and override it in the derived class, which you can see from the method called
SomeActionin this example:If a method is overriden, then the new behaviour will be exhibited regardless of whether you reference it as the base type or the derived type.
(If you use the
newkeyword, or don’t put anything, then a new inheritance chain is created and the behaviour will depend upon whether you reference the object as the base type or the derived type. You can see this in the final two calls in the code above: for the overriden method the derived behaviour is used but for the method where ‘new’ was used the orginal behaviour is exhibited when the object is treated as aBase.)