I hereby declare this week as the week of the enumerator. ;-)
Hallvard Vassbotn started this week with an excellent post on using enumerators patterns on your own collections. You should really give this high School enumeration stuff, a read!
The .NET Framework it self offers a lot of basic functionality for enumerators. It is friday so let's take a look on some basics here:
Sometimes it is necessary to let a user pick a value from a enumerator type. For example you want the user to pick some property value of a component, which is enumerator. You could, of course, fill a combox with string values by hand (keeping the order), but in future releases the list could extended, having you to alter your code.
Looping an enumerator
It is easier then to simply loop through the enumerator type. Update! In Delphi win32 this is not possible. This is false! Uli commented that it can in Delphi Win32!, using the Typinfo unit. (See the code in the comments)
In .NET however this is possible using the Enum.GetNames method.
In C# you code looks like this:
foreach ( string s in Enum.GetNames(typeof(SeriesChartType)) )
{
Messagbox.Show(s);
}
the equivalent code in Delphi .NET is:
for s in Enum.GetNames(TypeOf(SeriesChartType)) do begin
MessageBox.Show(s);
end;
Exists a value?
Check if a enumerator value exists in a enumerator type with the IsDefined method.
Delphi .NET code:
s := 'Point';
if Enum.IsDefined(TypeOf(SeriesChartType), s) then
MessageBox.Show('Yes')
else
MessageBox.Show('No');
Conclusion, the .NET framework Enum class, which is the base class for all the enumerator types, adds valueable methods to the basic enumerator types.
More information can be found on MSDN here.
6 comments:
In Delphi win32 this is not possible.
Not quite true. It's just a bit more complicated:
program Project2;
uses
SysUtils,
Dialogs,
TypInfo;
type
SeriesChartType = (Point, FastPoint, Bubble, Line, Spline, StepLine);
procedure ListThem;
var
s: string;
t: SeriesChartType;
begin
for t := Low(SeriesChartType) to High(SeriesChartType) do
begin
s := GetEnumName(TypeInfo(SeriesChartType), Ord(t));
ShowMessage(s);
end;
end;
procedure CheckFor(const AName: string);
var
i: Integer;
begin
i := GetEnumValue(TypeInfo(SeriesChartType), AName);
if i >= 0 then
ShowMessage(AName + ': Yes')
else
ShowMessage(AName + ': No');
end;
begin
ListThem;
CheckFor('Bubble');
CheckFor('hgfkhg');
end.
Uli,
I stand corrected! ;-)
I did not know about the Typinfo unit. Always great to learn something new!
Thanks!
> Always great to learn something new!
Indeed. Therefore I appreciate blogs like yours, Hallvard's or Primmoz's. :-)
BTW: How did you get your code fragments formatted? Is that available in the comments section too?
> Primmoz
Sorry, Primoz. :-)
Uli,
In windowslive writer, I just select the code fragment and press tab. (Is a blockquote) This does not work in the comments. (not all HTML is allowed)
As far as I can tell, this post is about enumerations (enums), not enumerators.
Post a Comment