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

Recommended Answers

All 4 Replies

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();
commented: Upvoted for being quicker than me +5

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.

commented: 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"

Make alert virtual and override it in class b.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.