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

Posted by Sean O'Connor on Stack Overflow See other posts from Stack Overflow or by Sean O'Connor
Published on 2011-11-30T01:48:25Z Indexed on 2011/11/30 1:50 UTC
Read the original article Hit count: 162

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about Windows

Related posts about inheritance