Alan B
Alan B

Reputation: 2289

Abstract class member inaccessible due it's protection level

How do I access a protected member of an abtsract class? Assume I have classes defined as below

public abstract class BaseClass
{
    private int index ;

    protected int GetIndex
    {
        get { return index ;}
        set { index = value; }
    }
}

public class MyClass : BaseClass
{
     ...
}

public class TestClass
{
     var data = new MyClass()
     var index = data.GetIndex;
}

The line

var index = data.GetIndex;

complains that inaccessible due it's protection level. How do I access the GetIndex property of MyClass in TestClass?

-Alan-

Upvotes: 0

Views: 1353

Answers (2)

Mr Luk
Mr Luk

Reputation: 53

Use this:

public abstract class BaseClass
{
    public int GetIndex { get; private set; }

    public BaseClass() { GetIndex = 0; }
}

Then you can set GetIndex only in BaseClass (your veriable index is private) or:

public abstract class BaseClass
{
    private int index;

    public int GetIndex 
    { 
        get { return index; } 
        protected set { index = value; } 
    }
}

Upvotes: 1

GhostCat
GhostCat

Reputation: 140407

Your problem is exactly what protected is meant to be used for.

It protects fields/methods from being used from outside of the base class or sub classes. TestClass is not derived from BaseClass or MyClass; and does you can't get to GetIndex. It is as simple as that.

Thus, your option space is:

  1. Replace protected on BaseClass
  2. Provide other means in MyClass to retrieve/set that property
  3. Change TestClass to derive from BaseClass

No specific ordering in that list; but obviously, option 3 being the "worst" alternative here.

Upvotes: 4

Related Questions