0

How do I get the string representation if I know the enum of integer value ?

type    
  MyEnum = (tmp_one, tmp_two, tmp_three);

const
  MyTypeNames: array[tmp_one..tmp_three] of string = ('One', 'Two', 'Three');
4
  • 2
    It is customary to name your types starting with T, like TMyEnum. Also, the members of the enum should be like meOne, meTwo, meThree. [Compare: TFontStyle = (fsBold, fsItalic, fsUnderline, fsStrikeOut); TWindowState = (wsNormal, wsMinimized, wsMaximized) etc.] Commented Oct 16, 2012 at 14:52
  • 3
    The question is unclear to me. I can only make assumptions of what the OP wants... Commented Oct 16, 2012 at 15:26
  • 2
    @kobik - I agree. I don't understand what does "knowing an enum of integer" mean? And also what does string representation mean, "tmp_one" or "One"? Commented Oct 16, 2012 at 16:10
  • Sorry the question was so unclear Commented Oct 16, 2012 at 17:01

3 Answers 3

6

I'm assuming that you have an ordinal value rather than a variable of this enumerated type. If so then you just need to cast the ordinal to the enumerated type. Like this:

function GetNameFromOrdinal(Ordinal: Integer): string;
begin
  Result := MyTypeNames[MyEnum(Ordinal)]; 
end;
Sign up to request clarification or add additional context in comments.

4 Comments

IMHO it is a bit overkill with a function. But of course you could argue that it is for illustrative purposes.
Why not just pass in a MyEnum parameter and avoid the typecast? The types are hard-coded already.
@Ken: I believe David took notice of the 'if I know the enum of integer value' part of the question.
@Andreas I made it a function because that's just an easy way to be explicit about the types of parameter and return value
6

I assume you want to use the names in your array of string. Then this is very simple:

var
  myEnumVar: MyEnum;
begin
  myEnumVar := tmp_two; // For example
  ShowMessage(MyTypeNames[myEnumVar]);

Comments

4

You don't need to use the ordinal values of your enum type. You can declare an array with the enum type as its "subscript" and use an enum var directly.

type    
  TMyEnum = (tmp_one, tmp_two, tmp_three);

const
  MyTypeNames: array[TMyEnum] of string = ('One', 'Two', 'Three');

function Enum2Text(aEnum: TMyEnum): string;
begin
  Result := MyTypeNames[aEnum]; 
end;

Call it with the enum or an integer value cast to the enum:

Enum2Text(tmp_one);     // -> 'One'
Enum2Text(TMyEnum(2));  // -> 'Three'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.