I've read this question about using Clone()
and want to know if what I'm after will be achieved. My understanding from reading that question is that Clone()
does a shallow copy, however reading elsewhere led me to believe differently, and now I'm confused.
Our project has a class Rule
that has an ICollection<ICondition> Conditions
. We'd like to provide users with a shortcut method to duplicate an existing Condition
and modify it rather than start from scratch. To that end, we're providing a Copy To New
button.
ICondition
looks like this:
interface ICondition
{
long ID { get; set; }
string Description { get; set; }
DateTime EffectiveDate { get; set; }
string IfStatement { get; set; }
string PriceVersion { get; set; }
PriceDetail Pricing { get; set; }
bool StandardOption { get; set; }
}
Given what I've read about Clone()
, I'm fairly confident it would work the way I expect by using ICondition newCondition = conditionToCopy.Clone()
, though I'm unsure if Pricing
would be duplicated correctly, since it's a complex data type.
So, the first part of my question is, "will this work?" I would just try it and see, however ICondition
(or really its underlying Condition
) doesn't seem to provide a method for Clone()
, which leads me to the second part of my question: can I leverage IClonable
to enable this functionality? If so, where?
Is this the way?
public static class Condition : IClonable
{
...
public Condition Clone(Condition conditionToClone)
{
return new Condition
{
Description = this.Description,
EffectiveDate = this.EffectiveDate,
IfStatement = this.IfStatement,
PriceVersion = this.PriceVersion,
Pricing = this.Pricing,
StandardOption = this.StandardOption
}
}
}
And, given that as the answer, is there any utility to declaring IClonable
as the interface? Does it add any value?
Update:
Based on the below answer, I decided to do this, which at least builds (and hopefully runs; haven't tried it yet):
public class Condition
{
...
public Condition Clone()
{
return (Condition)base.MemberwiseClone();
}
}
I still don't see the need for ICloneable
, so have left it out. The compiler was complaining about it anyway, something about the base class not being object
.