namespace System
{
//
// Summary:
// Supports cloning, which creates a new
instance of a class with the same value
// as an existing instance.
[ComVisible(true)]
public interface ICloneable
{
//
// Summary:
// Creates a new object that is a copy of the
current instance.
//
// Returns:
// A new object that is a copy of this
instance.
object Clone();
}
}
class Person : ICloneable
{
public string
FirstName { get; set; }
public string LastName
{ get; set; }
public DateTime BirthDate { get; set; }
public int Age
{
get
{
var today = DateTime.Today;
var age = today.Year - BirthDate.Year;
return BirthDate > today.AddYears(-age) ? --age : age;
}
}
public override string
ToString()
{
return $"{Age}) {FirstName} {LastName}";
}
public int
CompareTo(Person other)
{
return Age - other.Age;
}
public object Clone()
{
return new Person
{
FirstName = this.FirstName,
LastName = this.LastName,
BirthDate = this.BirthDate
};
}
}
class Program
{
static void Main(string[] args)
{
var p1 = new Person {
FirstName = "Pawel",
LastName = "Ciucias",
BirthDate = new DateTime(1984, 1, 31)
};
var p2 = p1.Clone() as Person;
Console.WriteLine(p1.ToString());
Console.WriteLine(p2.ToString());
p1.FirstName = "Tomek";
p1.BirthDate = new DateTime(1988, 6, 28);
Console.WriteLine(p1.ToString());
Console.WriteLine(p2.ToString());
}
}
public object Clone()
{
return this;
}