public interface ICloneable { object Clone(); } class Person : ICloneable { public string Name { get; set; } public int Age { get; set; } public object Clone() { return new Person { Name = this.Name, Age = this.Age }; } } class Program { static void Main(string[] args) { Person p1 = new Person { Name="Tom", Age = 23 }; Person p2 = (Person)p1.Clone(); p2.Name = "Alice"; Console.WriteLine(p1.Name); // Tom Console.Read(); } } 

Question: Why is an instance of p1 cast to Person type when calling the Clone () method? After all, it is also a Person object.

  • one
    [KO mode ON] Because Clone () returns object [KO mode OFF] ICloneable.Clone - method () - Mirdin
  • one
    Indeed - public object Clone (). Thank you for helping an inattentive student. - Proshka
  • one
    The type of Person is not p1 , but the result of executing p1.Clone() - qzavyer
  • Understood thanks. - Proshka

1 answer 1

The public object Clone() method public object Clone() returns an object of type object . Therefore, the cast is necessary.