Monday, March 26, 2012

OO 101

hi,

im trying to set a base class property value from child class using C#, is that possible


public class B : A
{
const int i = 1; // i want to set the base i to 1
}

public class A
{
int i;
int j;
A()
{
y = i; // here i want y to be 1
}
}


what should i do .. virtual.. !!?declare i as protected then simply set i in the subclass.

protected int i;

FYI, your B class is currently declaring a new field i. To use/set the i as I show above you will have to do that in a method, not in the subclasses (B) definition of fields.
so you're saying this will work?


class B : A
{
B()
{
i = i +1;
}
}

class A
{
int i;
A()
{
System.Console.Write(i);
}
}

what's the ouput 0 or 1?
First of all the posted code will not work/compile it should be defined like this


public class B : A {
public B() {
i = i +1;
//or a C# shortcut
// i++;
}
}
public class A {
protected int i;
public A() {
System.Console.Write(i);
}
}

Now if you execute this line of code somewhere

B b = new B();

When B is constructed the compiler see's that is derived from class A and will call A's default constructor so 0 will print to console. Now B's default constructor will be executed and i will be incremented by 1.

Since i is declared as protected it will only be available to B's internal methods, i.e., you cannot access i like this

int x = b.i;

Hope this helps.

0 comments:

Post a Comment