How do I tell which case is valid in a variant record when the case variable isn't named, and how do I create values of such records?

Viewed 2787

I've been reading about "case" within records and I still have some open questions about it. (http://www.delphibasics.co.uk/Article.asp?Name=Records)

I use the example:

type 
   TRect = packed record
     case Integer of
       0: (Left, Top, Right, Bottom: Integer);
       1: (TopLeft, BottomRight: TPoint);
   end; 

The example basically tells me that the first member/property of TRect is an Integer (which this Integer has no name!). If this (unnamed!) integer is 0 or 1 it just adds the corresponding members:

(0 for Left, Top, Right, Bottom)
(1 for TopLeft, BottomRight) 

So let's say there is content in memory which I would like to use this record on. I fairly add a new type that represents a pointer to TRect. The new record would look like this:

type
   PRect = ^TRect; 
   TRect = packed record
     case Integer of
       0: (Left, Top, Right, Bottom: Integer);
       1: (TopLeft, BottomRight: TPoint);
   end; 

So the content (in memory) would sorta like this:

First Integer = 0 // determines the case!
Left          = 1
Top           = 2
Right         = 3
Bottom        = 4

This content has a total size of 20 bytes in memory and has the address of X.

To output my content I would typecast this address like this: PRect(X)

Now how do I know my record has the "0" or the "1" case?!

How could I also create a record with the case of "0" or "1"?

I'm extremely confused by this and would like to know if I understood the use of case in records...

3 Answers

When the case contain no identifier, the different cases can be read meaningfull at any time, because a Tpoint and two integers are binary compatible. Since there are no identifier, the integer in the case statement is a dummy, that takes up no space in the record.

Trect = packed record
  case Integer of
    0: (Left, Top, Right, Bottom: Integer);
    1: (TopLeft, BottomRight: TPoint);
end; 

When the case contains an identifier, eg

type tperson = record
  case married : boolean of
  true :  (dateofmarriage : tdate);
  false : (evermarried : boolean; dateofdivorce  : tdate);  
end;

by examine married, you now which of the recordstructures to use.

Related