Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign base object of child object

Tags:

c#

inheritance

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
like image 916
fhnaseer Avatar asked Mar 23 '23 11:03

fhnaseer


1 Answers

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.

like image 109
haim770 Avatar answered Mar 26 '23 01:03

haim770