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.

Answers


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.


Need Your Help

Regular Expression to check for words

regex

Here is my regular expression:

Can we access mail folders of outlook in Windows service? How?

c# windows-services outlook-addin

I have created outlook addin in C# to sync mails from our website. Now I want to sync those mails after some time interval in background. Can we access mail folders of outlook into the windows serv...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.