Search code examples
c#classpropertiesxna

how do i "link" to a property in another class


i have a class (say classA) that contains a string property.

i want to set it to a string property from another class (say classB) so that when i change the property into classA it changes in classB and visa versa.

i know i can do this with functions by using ref but when i try it on my class (Constructor) it doesn't work

here is what i have;

public class myClass 
{
    public string Name;
    public int Image;
    public myClass(ref string myName)
    {
        Name = myName;
    }

    public  void changeIt()
    {
        Name = "xyz";
    }

}

And my main code;

string myString = "abc";
Console.WriteLine("myString:"+myString);
myClass mClass = new myClass(ref myString);
mClass.changeIt();
Console.WriteLine("myString (After doThis):" + myString);
Console.ReadLine();

when i run it it produces;

myString:abc
myString (After doThis):abc

is there something i am missing here? why doesn't it change to xyz?


Solution

  • Generally speaking, a change in the state of an object should be communicated with an event.

    So in the class that has the "important" property, when you change its value an event should be fired.

    The other classes should be suscripted to this event and catch it.

    You can add the value of the changed string to the fired event so that you won't even need to reference the object when the string value has changed.

    You can see how events work in C# on this link.

    An example of how to do it can be as follow:

    class ClassWithImportantProperty
    {
        string myString = string.Empty;
    
        public string MyImportantProperty
        {
            get { return myString; }
            set
            {
                myString = value;
                if (PropertyChanged != null)
                    PropertyChanged(myString, EventArgs.Empty);
            }
        }
    
        public event EventHandler PropertyChanged;
    }
    
    class SecondClass
    {
        public string MyDependantString { get; set; }
    
         public secondClass()
         {
             var classInstance = new ClassWithImportantProperty();
             classInstance.PropertyChanged += classInstance_PropertyChanged;
         }
    
         void classInstance_PropertyChanged(object sender, EventArgs e)
         {
             MyDependantString = sender.ToString();
         } 
    }
    

    Basically you have a class that fires an event every time one of it's properties change. Then another class that is suscribed to this event and every time it gets fired, it does some process of it's own.