I have little problem using inheritance. I can neither change the value of first and second in class C nor first in class B when they are protected. If these variables are public everything works fine, but in this case what's the point of using protected?
class A
{
protected int first { get; set; }
}
class B : A
{
protected int second { get; set; }
public Show()
{
A a = new A();
a.first = 5;
}
}
class C : B
{
private int third { get; set; }
static void Main()
{
B b = new B();
b.first = 1;
b.second = 2;
}
}
The main problem is simply caused by you putting your program's entry point inside the class you want to test. Because Main()
is static, you can't access C
's (inherited) instance members.
So separate it:
class Program
{
static void Main()
{
C c = new C();
c.Test();
}
}
Your class C
inherits from B
, so C
can access B
's protected members like so:
class C : B
{
private int third { get; set; }
public void Test()
{
first = 1; // from A
second = 2; // from B
third = 3; // from C
}
}
By new
ing a B
inside C
, there's no relation between those instances of B
and C
, so all you can access there are B
's public
and internal
members.