1

I am new at C# Let's say I have 4 Classes:

Holder:

public class Holder
{
    private string name;
    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }
}

SecondClass:

public class SecondClass
{
    public void SecondClassMethod()
    {
        Holder holder = new Holder();
        holder.Name = "John";
        Console.WriteLine(holder.Name + " from SecondClass");
    }
}

AnotherClass:

public class AnotherClass
{
    public void AnotherClassMethod()
    {
        Holder holder = new Holder();
        holder.Name = "Raphael";
        Console.WriteLine(holder.Name + " from AnotherClass");
    }

}

and final Program class:

class Program
{
    static void Main(string[] args)
    {
        Holder x1 = new Holder();
        SecondClass x2 = new SecondClass();
        AnotherClass x3 = new AnotherClass();

        x1.Name = "Nobody";
        Console.WriteLine(x1.Name);
        x2.SecondClassMethod();
        Console.WriteLine(x1.Name);
        x3.AnotherClassMethod();
        Console.WriteLine(x1.Name);

        Console.ReadLine();            
    }
}

Output after running program:

Nobody
John from SecondClass
Nobody
Raphael from AnotherClass
Nobody

My Question is: How I can get proper name (given by that other classes) using Program class ? Thing is I want to use that set,get on Holder class. I can't figure it out.

I want to get:

Nobody
John from SecondClass
John
Raphael from AnotherClass
Raphael

as output

rafixwpt
  • 145
  • 3
  • 9

2 Answers2

4

You're instantiating a new instance of Holder in each class. In order to modify the existing instance, you need to pass a reference to the other classes.

You can do that by introducing a constructor, where you store a reference to the Holder instance in a private (preferably readonly) field:

public class SecondClass
{
    private readonly Holder _holder;
    public SecondClass(Holder holder)
    {
        _holder = holder;
    }

    public void SecondClassMethod()
    {
        _holder.Name = "John";
        Console.WriteLine(_holder.Name + " from SecondClass");
    }
}

Then change the code using that class:

Holder x1 = new Holder();
SecondClass x2 = new SecondClass(x1);
Community
  • 1
  • 1
CodeCaster
  • 131,656
  • 19
  • 190
  • 236
1

Also, you can use a public property in your classes to store the reference of the Holder instance that you want to modify:

public class SecondClass
{
    public Holder Holder { get; set; }

    public SecondClass(){}

    public void SecondClassMethod()
    {
        if (Holder!=null)
        {
            Holder.Name = "John";
            Console.WriteLine(Holder.Name + " from SecondClass");
        } 
    }
}

And then in Main method you could do this:

Holder x1 = new Holder();
SecondClass x2 = new SecondClass(){Holder=x1};
x2.SecondClassMethod();
octavioccl
  • 35,665
  • 6
  • 76
  • 95