If I have a class that contains some properties and methods, and when a property is changed, it fires an event (in this case passing a string in the args):
public class Settings
{
public delegate void SettingsChangedHandler(object sender, string e);
public event SettingsChangedHandler SettingsChanged;
private string rootfolder;
public string RootFolder
{
get { return rootfolder; }
set
{
rootfolder = value;
if (SettingsChanged != null)
SettingsChanged(this, "ROOT_FOLDER");
}
}
}
If i have somewhere in my code:
public Settings SettingsInstance = new Settings();
SettingsInstance.SettingsChanged += new SettingsChangedHandler(SettingsInstance_SettingsChanged);
SettingsInstance = SomeOtherSettingsInstance;
I want all of the properties that have changed to fire their events.
How do I achieve something like this? Surely I don’t have to copy them over one at a time?
This line of code:
does not copy anything inside the objects, instead it overwrites the reference stored in SettingsInstance with the reference stored in SomeOtherSettingsInstance.
The object itself is none the wiser.
Basically, after you have executed the first of the 3 last lines, you have this scenario:
After you’ve executed the third line, this is how it looks:
Now you have two references to the first object, one through each variable, and you’ve left the new object you just created to rot for the garbage collector to come pick it up later.
If you wish to copy the internals, then yes, you have to copy one property at a time.
I regularly create cloning support like this:
In your scenario, you want to hook up an event before copying things, so you would call it like this:
The reason I implement cloning support like that is due to object hierarchies. If that is not an issue for you (you’re not going to inherit from Settings), you can just do this: