i can't create a clone method for my business entity  
Author Message
R.Tutus





PostPosted: Visual C# General, i can't create a clone method for my business entity Top

Hi, this doesn 't seem right, the Clone method defined at the end of the class gives me a syntax error and I don t know the syntax for creating implements in C#.

public class CustomerEntity: ICloneable
{

private string _FirstName;
public string FirstName
{
get { return _FirstName; }
set
{
_FirstName = value;
_isDirty = true;
}
}

public object Clone : System.ICloneable.Clone
{
CustomerEntity newClone=new CustomerEntity();
newClone.FirstName= _FirstName;
return newClone;

}
}

P.S: I didn t create any thing outside the class. Thanks for your help a lot.




Visual C#6  
 
 
Keith Rome





PostPosted: Visual C# General, i can't create a clone method for my business entity Top

You have two options, Explicit or Implicit interface implementation:

Implicit implementation first:

public class CustomerEntity : ICloneable

{

private string _FirstName;

public string FirstName

{

get { return _FirstName; }

set

{

_FirstName = value;

_isDirty = true;

}

}

public object Clone()

{

CustomerEntity newClone = new CustomerEntity();

newClone.FirstName = _FirstName;

return newClone;

}

}

And then there is explicit implementation (I personally prefer this style):

public class CustomerEntity : ICloneable

{

private string _FirstName;

public string FirstName

{

get { return _FirstName; }

set

{

_FirstName = value;

_isDirty = true;

}

}

object ICloneable.Clone()

{

CustomerEntity newClone = new CustomerEntity();

newClone.FirstName = _FirstName;

return newClone;

}

}

The main difference is that when explicitly implementing an interface, the method is a special form of private scoped method where you actually need to explicitly cast the object to ICloneable before you can call .Clone() on it.

HTH