0

Hi
i created class a and b is it's child (a:b)

public class a
    {
         string text = "class a";
        public void alert()
        {
            MessageBox.Show(text);
        }
    }
    public class b : a
    {
        string text = "class b";

    }
 b myb = new b();
            myb.alert();

but when i call alert() it shows "class a"
how i can access child class varibles

3
Contributors
4
Replies
24
Views
4 Years
Discussion Span
Last Post by sepp2k
2

Something like this? (Note that a new string is not needed, just change the old one inside the derived class's constructor)

public class a
{
    public string text = "class a";
    public void alert()
    {
        MessageBox.Show(text);
    }
}
public class b : a
{
    public b()
    {
        text = "class b";
    }
}

/* ....... */

b myb = new b();
myb.alert();

Edited by TheApex

Votes + Comments
Upvoted for being quicker than me
2

Instead of defining a new variable with the same name, you could just assign a different value to the same variable, like this:

public class a
{
    protected string text = "class a";
    public void alert()
    {
        MessageBox.Show(text);
    }
}

public class b : a
{
    public b() {
        text = "class b";
    }
}

This way a b object will only have one variable named text, which will be the one inherited from a (and thus also the one accessed by a methods). And the value of that variable will be "class b" for b objects and "class a" for a objects.

Edited by sepp2k

Votes + Comments
you explained it better
0

thanks it's problem was sloved but another question i have

 public class a
    {
         public void alert()
        {
            MessageBox.Show("this is class a");
        }
       public void test()
        {
            alert();// calls just class a
        }
    }
    public class b : a
    {
         public void alert()
        {
            MessageBox.Show("this is class b");
        }
    }

 b myb = new b();
            myb.test();//shows  "this is class a"

how i can show "this is class b"

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.