Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing private variable to base class constructor

Tags:

c#

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)
    {
    }
}
like image 736
Bharadwaj Avatar asked Oct 30 '22 16:10

Bharadwaj


1 Answers

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.

like image 142
2 revs Avatar answered Nov 15 '22 06:11

2 revs