Bharadwaj
Bharadwaj

Reputation: 2553

Passing private variable to base class constructor

I want to pass a value to the base class constructor. The problem which I am facing is that the value is stored in a private variable inside derived class. Is it possible to pass it? or is it a good approach to do like this?

This is what I tried

class Filtering : Display
{
    private int length = 10000;
    public Filtering():base(length)
    {
    }
}

It is showing

An object reference is required for non-static field, method or property

Base class

abstract class Display
{
    public Display(int length)
    {
    }
}

Upvotes: 5

Views: 1592

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70671

Exactly as answerer Chips_100 wrote in his answer (currently deleted by owner):


If you want length to be an instance variable, but still supply it to the base constructor, I would suggest something like the following:

private const int DefaultLength = 10000;

private int length = DefaultLength;

public Filtering() : base(DefaultLength)
{
}

I haven't seen any indication the original author of this answer is inclined to undelete his own post. At the same time, while I would have written basically the same thing, I'd rather not take credit for an answer already present, authored by someone else. So I've converted this to a Community Wiki answer.

Upvotes: 2

Related Questions