Getting error when trying to access a protected accessor property of a base class in a derived class
namespace PalleTech
{
public class Parent
{
private int test = 123;
public virtual int TestProperty
{
// Notice the accessor accessibility level.
set {
test = value;
}
// No access modifier is used here.
protected get { return test; }
}
}
public class Kid : Parent
{
private int test1 = 123;
public override int TestProperty
{
// Use the same accessibility level as in the overridden accessor.
set { test1 = value / 123; }
// Cannot use access modifier here.
protected get { return 0; }
}
}
public class Demo:Kid
{
public static void Main()
{
Kid k = new Kid();
Console.Write(k.TestProperty);
}
}
}
Error 1 Unable to access protected member "PalleTech.Parent.TestProperty" via qualifier of type "PalleTech.Kid"; qualifier must be of type "PalleTech.Demo" (or derived from it)
source to share
From the MSDN article "A protected member of a base class is only available in a derived class if it is accessed through a derived class type."
This is where you access the Kid protected setter with an instance of it. You must create an instance of the Demo class and access through it.
source to share
The Getter TestProperty
in class Kid
is protected, which means that if you write a class derived from a class Kid
, you can access TestProperty
; if you instantiate a class Kid
you cannot access it.
You can change the behavior by removing protected
both classes from the settings;
public class Parent
{
private int test = 123;
public virtual int TestProperty
{
// Notice the accessor accessibility level.
set
{
test = value;
}
// No access modifier is used here.
get { return test; }
}
}
public class Kid : Parent
{
private int test1 = 123;
public override int TestProperty
{
// Use the same accessibility level as in the overridden accessor.
set { test1 = value / 123; }
// Cannot use access modifier here.
get { return 0; }
}
}
source to share