Reputation: 2289
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
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
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:
No specific ordering in that list; but obviously, option 3 being the "worst" alternative here.
Upvotes: 4