Search code examples
classvariablesinterfaceimplementationderived

c# implemented interface variable used in derived class


I am trying to implement an interface method in class A, and through that realization I want to give variable g value from input and then be able to read that g value in other derived classes. The problem is, non of the derived classes are able to see that value. What seems to be the problem?

interface ISomething
{
    void something(string some);
}
public class A : ISomething
{
    public string g;
    public void something(string some)
    {
        g = some;
    }
}
public class B : A
{
    public void methodB()
    {
        Console.WriteLine($"Printing g value from method B: {g}");
    }

}
public class C : A
{
    public void methodC()
    {
        Console.WriteLine($"Printing g value from method C: {g}");
    }
}
public class D : B
{
    public void methodD()
    {
        Console.WriteLine($"Printing g value from method D: {g}");
    }
}

static void Main(string[] args)
    {
        Console.WriteLine("Input something: ");
        string x = Console.ReadLine();
        A a = new A();
        a.something(x);
        B b = new B();
        C c = new C();
        D d = new D();
        b.methodB();
        c.methodC();
        d.methodD();
        Console.ReadKey();
    }

Solution

  • Just because B, C, D inherit from A does not mean their field g will get initialized to anything. Each object created is still an independent object, just because you declared an object of type A does not mean every class instance that inherit from A are going to hold the same field value as the instance of A that you create. You should be setting the field g of each derived class by calling the something() method, so change your code to this:

    B b = new B();
    C c = new C();
    D d = new D();
    d.something(x);
    c.something(x);
    b.something(x);
    b.methodB();
    c.methodC();
    d.methodD();