Home > database >  How to access variables in subclasses?
How to access variables in subclasses?

Time:11-24

Lets say I have three classes, p, p1 and p2

public class p 
{
  public p() {}
}

public class p_1 : p
{
  public p_1() {}
  public string tester = "ABC";
}

public class p_2 : p
{
  public p_2() {}
  public string foo = "Test";
}

Now I want to create a general variable of the type p and then use it as type p_1. Then I want to access the variable tester inside.

p p_tester;
p_tester = new p_1();
Console.Writeline(p_1.tester);

My question is: Why can't I access the .tester variable? Am I missing something? Visual studio wants me to declare all variables from the subclasses in the main class... but that is not what I want.

Is that what I try to do even possible?

CodePudding user response:

The only way I've found to do this is to cast p_tester as p_1. The one thing I'm sure is that you can't access p_1 directly because your class is not static. You can only access the declared instance p_tester

p p_tester;
p_tester = new p_1();
Console.WriteLine(((p_1)p_tester).tester);

CodePudding user response:

Your declare function is wrong. Why not access it through the child class?

    p_1 p_tester;
    p_tester = new p_1();
    Console.WriteLine(p_tester.tester);

If you want to access the tester form child class p_1() then you could set the tester as static variable.

    public class p_1 : p
    {
      public p_1() {}
      public static string tester = "ABC";
    }

    Console.WriteLine(p_1.tester);
  • Related