I am just trying to learn variant records.Can someone explain how Can I check shape in record whether it is rectangle/Triangle etc. or any good example with implementation available ? I had checked variants record here but no implementation available..
type
    TShapeList = (Rectangle, Triangle, Circle, Ellipse, Other);
    TFigure = record
    case TShapeList of
      Rectangle: (Height, Width: Real);
      Triangle: (Side1, Side2, Angle: Real);
      Circle: (Radius: Real);
      Ellipse, Other: ();
   end;
                You have to add a field for the shape like so:
type
    TShapeList = (Rectangle, Triangle, Circle, Ellipse, Other);
    TFigure = record
    case Shape: TShapeList of
      Rectangle: (Height, Width: Real);
      Triangle: (Side1, Side2, Angle: Real);
      Circle: (Radius: Real);
      Ellipse, Other: ();
   end;
Note the Shape field.
Also note that this doesn't imply any automatic checking by Delphi - you have to do that yourself. For example, you could make all the fields private and allow access only through properties. In their getter/setter methods you could assign and check the Shape field as needed. Here's a sketch:
type
  TShapeList = (Rectangle, Triangle, Circle, Ellipse, Other);
  TFigureImpl = record
    case Shape: TShapeList of
      Rectangle: (Height, Width: Real);
      Triangle: (Side1, Side2, Angle: Real);
      Circle: (Radius: Real);
      Ellipse, Other: ();
  end;
  TFigure = record
  strict private
    FImpl: TFigureImpl;
    function GetHeight: Real;
    procedure SetHeight(const Value: Real);
  public
    property Shape: TShapeList read FImpl.Shape;
    property Height: Real read GetHeight write SetHeight;
    // ... more properties
  end;
{ TFigure }
function TFigure.GetHeight: Real;
begin
  Assert(FImpl.Shape = Rectangle); // Checking shape
  Result := FImpl.Height;
end;
procedure TFigure.SetHeight(const Value: Real);
begin
  FImpl.Shape := Rectangle; // Setting shape
  FImpl.Height := Value;
end;
I split the record in two types because otherwise the compiler wouldn't accept the visibility specifiers as they are needed. Also I think it's more readable and the GExperts code formatter doesn't choke on it. :-)
Now something like this would violate an assertion:
procedure Test;
var
  f: TFigure;
begin
  f.Height := 10;
  Writeln(f.Radius);
end;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With