sigil
sigil

Reputation: 9556

How to pass a derived class property to the constructor of a base class

Here's my base class:

class baseClass
{
 string fileContents; 

 public baseClass(string filePath)
 {
  fileContents=getContents(filePath);
 }

}

I have a derived class where the file path will always be the same. Ideally I would like to pass that file path as follows:

class derivedClass:baseClass
{
 string specialFilePath=@"x:\abc.def";

 public derivedClass():base(specialFilePath)
 {
 }
}

But this gives me a compile error:

An object reference is required for the non-static field, method, or property 'derivedClass.specialFilePath'

If I understand correctly, this is happening because the baseClass constructor gets called first, before derivedClass has a chance to create specialFilePath. How can I pass this string back to the base class' constructor?

Upvotes: 2

Views: 1453

Answers (3)

McGarnagle
McGarnagle

Reputation: 102793

Make "specialFilePath" static, and this will work -- static members are initialized before the constructors run.

class derivedClass:baseClass
{
    static string specialFilePath=@"x:\abc.def";

    public derivedClass():base(specialFilePath)
    {
    }
}

Upvotes: 4

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

You might not even need a field if you do something like this.

class derivedClass : baseClass
{
    public derivedClass()
        : base(@"x:\abc.def")
    {
    }
}

Upvotes: 3

celerno
celerno

Reputation: 1387

That's because at the time when you want to access to your property specialFilePath, it hasn't been initialized. Make it static.

Upvotes: 2

Related Questions