Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pascal

What are indexed properties in Pascal classes?

Samia Ishaque

Overview

Indexed properties are used to define a property along with its read and write specifiers. The read and write specifiers must be a function and procedure, respectively. Indexed properties help us define common read and write specifiers for properties of the same type.

Example

The following example will help you understand indexed properties better. As shown below, I wish to set Var1 and Var2 of the type integer using one setter function and read the variables using a getter procedure.

Using property, I give each variable an index number and define the getter procedure and setter function. The index number helps the function and procedure identify which property is being referred to, Num1 or Num2. This lets us set the values for Var1 and Var2 in the final code and print out the values.

{$mode objfpc}  
Type  
  ClassName = Class  
  Private  
    Var1,Var2 : Integer;  
    Function GetNum (Index : Integer): Integer;  
    Procedure SetNum (Index : Integer; Value : Integer);  
  Public  
    Property Num1 : Integer index 1 read GetNum Write SetNum;  
    Property Num2 : Integer index 2 read GetNum Write SetNum;  
  end;  

Procedure ClassName.SetNum (Index : Integer; Value : Integer);  
begin  
  Case Index of  
   1 : Var1 := Value;  
   2 : Var2 := Value;  
  end;  
end;  
 
Function ClassName.GetNum (Index : Integer) : Integer;  
begin  
  Case Index of  
   1 : Result := Var1;  
   2 : Result := Var2;  
  end;  
end;  
 
Var  
  Example : ClassName;  
 
begin  
  Example := ClassName.create;  
  Example.Var1 := 20;  
  Example.Var2 := 21;  
  With Example do  
    WriteLn ('Number 1=',Num1,' Number 2',Num2);  
end. 

RELATED TAGS

pascal

CONTRIBUTOR

Samia Ishaque
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring