Sean O'Connor
Sean O'Connor

Reputation: 3

C# Function Inheritance--Use Child Class Vars with Base Class Function

Good day, I have a fairly simple question to experienced C# programmers. Basically, I would like to have an abstract base class that contains a function that relies on the values of child classes. I have tried code similar to the following, but the compiler complains that SomeVariable is null when SomeFunction() attempts to use it.

Base class:

public abstract class BaseClass
{
    protected virtual SomeType SomeVariable;

    public BaseClass()
    {
         this.SomeFunction();
    }

    protected void SomeFunction()
    {
         //DO SOMETHING WITH SomeVariable
    }
}

A child class:

public class ChildClass:BaseClass
{
    protected override SomeType SomeVariable=SomeValue;
}

Now I would expect that when I do:

ChildClass CC=new ChildClass();

A new instance of ChildClass should be made and CC would run its inherited SomeFunction using SomeValue. However, this is not what happens. The compiler complains that SomeVariable is null in BaseClass. Is what I want to do even possible in C#? I have used other managed languages that allow me to do such things, so I certain I am just making a simple mistake here.

Any help is greatly appreciated, thank you.

Upvotes: 0

Views: 299

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

You got it almost right, but you need to use properties instead of variables:

public abstract class BaseClass {
    protected SomeType SomeProperty {get; set}
    public BaseClass() {
         // You cannot call this.SomeFunction() here: the property is not initialized yet
    }
    protected void SomeFunction() {
        //DO SOMETHING WITH SomeProperty
    }
}
public class ChildClass:BaseClass {
    public ChildClass() {
        SomeProperty=SomeValue;
    }
}

You cannot use FomeFunction in the constructor because SomeProperty has not been initialized by the derived class. Outside of constructor it's fine, though. In general, accessing virtual members in the constructor should be considered suspicious.

If you must pass values from derived classes to base class constructor, it's best to do it explicitly through parameters of a protected constructor.

Upvotes: 1

Related Questions