I have a base class and a child class. Base class contains some variables and child contains some variables.
What I need to do is that when I create object of child class, I pass base class object in its constructor which will set base class variables of child object.
Code:
public class BaseClass
{
public int BaseInteger;
public double BaseDouble;
public bool BaseBool;
}
public class ChildClass : BaseClass
{
public ChildClass(BaseClass baseClass)
{
this.base = baseClass; // I am trying to do this.
}
public int ChildInteger;
public string ChildString;
}
So is it possible what I am trying to do here. How? When I tried this code I got this error.
Use of keyword 'base' is not valid in this context
You have to realize that ChildClass
does not contain BaseClass
but rather inherits from it.
That is why you can access data and methods that were defined in the base class using the this
keyword (this.BaseInteger
for example).
And that is also why you cannot 'set' the BaseClass
of your ChildClass
, it doesn't contain one.
Nevertheless, there are some useful patterns to achieve what you're trying to do, for example:
public class BaseClass
{
protected BaseClass() {}
protected BaseClass(BaseClass initData)
{
this.BaseInteger = initData.BaseInteger;
this.BaseDouble = initData.BaseDouble;
this.BaseBool = initData.BaseBool;
}
public int BaseInteger;
public double BaseDouble;
public bool BaseBool;
}
public class ChildClass : BaseClass
{
public ChildClass() {}
public ChildClass(BaseClass baseClass) : base(baseClass)
{
}
public int ChildInteger;
public string ChildString;
}
Thanks to @svick for his suggestions.
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