Passing Class to Dialog

M

mcmalburg

I have a dialog box (form) that configures items in a class. I'm
wanting make sure that I handle OK and Cancel properly and that I also
manage memory (I hate the fact the C# supposedly does this for me).
Nonetheless, my question is regarding cloning. I'm assuming that I
have to clone my object into the dialog so that I can corrupt it in
the dialog and still hit "Cancel". Do I then need to clone it back
into the calling object when the user hits "OK" or can I just do a
"copy" (with the "=" operator)?

public class MyBaseClass
{
MySettingsClass myClassToConfigure ;

void CallADialog ()
{
DialogForm dlg = new DialogForm();
dlg.theClass =
(MySettingsClass)myClassToConfigure.Clone() ; // make a copy for the
dialog

if (dlg.ShowDialog() == DialogResult.OK)
{
myClassToConfigure = dlg.theClass ; // or should
I "Clone" it back?
}
} // end CallADialog

} // end MyBaseClass
 
M

Marc Gravell

Do I then need to clone it back
into the calling object when the user hits "OK" or can I just do a
"copy" (with the "=" operator)?

Well, "=" is only "copy" if we are talking about a struct; if this is
a class, then "=" simply assigns your variable to the existing
instance. In most cases, this should be fine.

However; due to some ambiguous naming a few years ago, it isn't
entirely clear whether Clone() means "deep clone" or "shallow clone",
so even in the "cancel" scenario it is possible that sub-components of
your class remain corrupted.

You could look at the "memento" pattern here; alternatively, for
simple data structures perhaps consider serializing/deserializing the
object (to binary or xml) to ensure you have a completely standalone
deep clone.

If your data is simple - pick a simple strategy. If you have complex
data then unfortunately you sometimes need complex code to handle
"undo" or "apply changes to existing object" scenarios.

Marc
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

It does depend of your object in question. Most of the time you pass your
instance to the dialog, onthe Load event the dialog copy those values to its
controls. then only when pressed Ok the dialog copies back the values to the
instance.

In this way you do not need to keep a copy of the original values.

In the weird case that the above cannot be applied take a look at
Serialization.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top