Search code examples
c#.nettypescasting

Is it possible to change an object's type from inside itself


I have a shape class with square and triangle as inheriting classes

Square square = new Square();
square.SideCount = 4;
//Logic
square.SideCount = 3;
 
if(square is Triangle)
   {
   //...

If I instantiate a new square with SideCount = 4, then if I change it's SideCount to 3, can I put code into the SideCount's Setter to convert Square to Triangle if sides are set to 3?


Solution

  • Not directly no, an instance of Square cannot be changed to an instance of Triangle.

    You could have a method, which returns an instance of Shape defined on the base class Shape:

    public abstract class Shape
    {
        public Shape Mutate(int numberOfSides)
        {
            // over simplified example:
            if(numberOfSides == 3)
               return new Triangle();
        }
    }
    
    public class Triangle : Shape {}
    public class Square : Shape {}
    

    usage

    var squ = new Square();
    var triangle = squ.Mutate(3);