Friday, August 19, 2011

Delphi Sets

A simple example of doing enumerator sets in Delphi. There are several other examples available, I will provide links at the end of this post.

1) Declare an enumerated type:
TeDaysOfWeek = (eDoWMonday, eDoWTuesday, eDoWWednesday, eDoWThursday, eDoWFriday, eDoWSaturday, eDoWSunday);

2) Declare a set of the enumerated type:
TeDaysOfWeekSet = set of TeDaysOfWeek;

3) Declare a variable to work with the set:
var
  eDOWSetWork: TeDaysOfWeekSet ;

4) Add items to the working set. Say the application is indicating what days the doctor is available:
// sets the set to empty
eDOWSetWork := [];
// add values to the set
if (some_boolean_values) then
begin
  eDOWSetWork := eDOWSetWork + [eDoWMonday, eDoWTuesday];
end;
if (some_other_condition) then
begin
  eDOWSetWork := eDOWSetWork + [eDoWWednesday];
end;

What you are doing with the "set = set + enumerator" is adding values into the set. You could also set the set:
eDOWSetWork := [eDoWWednesday];
This would replace any values in the set with just eDoWWednesday.

This sets the set for use, now we need to use it for comparison or other behavior:
5) Implement behavior:
procedure DoSomething(p_eDOWSetWork: TeDaysOfWeekSet);
begin
  if (eDoWWednesday in p_eDOWSetWork) then
  begin
  end;
end;

Other links for sets:
http://delphi.about.com/od/beginners/a/delphi_set_type.htm
http://www.delphibasics.co.uk/Article.asp?Name=Sets
Sets in Delphi Prism: http://prismwiki.codegear.com/en/Sets


No comments:

Post a Comment