Author Archives: jachguate

About jachguate

Entusiasta de la Tecnología de la Información, con una pasión desbordada por delphi y las bases de datos.

Generic class to convert a enum to string and viceversa

One of the things I always forget how to do, and hence I have to google to re-write the required code, is how to convert a enumerated type to string and a string to a enumerated type (EnumToStr, StrToEnum).

This is, first of all, because traditionally you have to write a different routine for each enumerated type you need, or worst, to directly call GetEnumName/GetEnumValue everywhere to do the hard work.

This is also due, in part, because until now I had no avail myself on the idea to have piece of code based on generics, that is reusable, and then save the routine into one of the libraries I usually have at hand while coding.

With this idea and after some effort, I wrote the class I share now with you, but first, take a look at how it is used, for example:

begin
  Memo1.Lines.Add(
    TEnumConverter<TAlign>.ToString(Self.Align));
end;

The basic idea is very simple and I hope the code speaks for itself. The good thing is you can call it with any enumerated type, including. of course, the custom types you defined, for example:

interface
type
  TMyEnum = (meValue1, meValue2, meValue3, meValue4);
 
implementation
 
procedure TForm1.Button1Click(Sender: TObject);
var
  MyEnum: TMyEnum;
begin
  MyEnum := meValue3;
  Memo1.Lines.Add(
    TEnumConverter<TMyEnum>.ToString(MyEnum));
end;

La clase TEnumConverter<T>

Above you’ll find the unit defining this class. You can also download it: UEnumConverter.pas

/------------------------------------------------------------------------------
//
// author: jachguate
//         http://jachguate.wordpress.com
//
// Disclaimer
//
// This code is provided "as is" without express or implied warranty of any
// kind
//
// The author disclaims all warranties with regard to this source code,
// including all implied warranties of merchantability and fitness for
// a particular purpose. I no event shall the author be liable for any
// special, indirect, incidental or consequential damages, or any damages
// whatsoever resulting from loss of use, data or profits, whether in an
// action of contract, negligence or other tortious action, arising out
// or in connection with the use, misuse or performance of this source code.
//
// You use it at your own risk
//
// This code is distributed free of charge.
//
// Attribution and beer is not required, but highly appreciated.
//
//------------------------------------------------------------------------------
 
unit UEnumConverter;
 
interface
 
type
  TEnumConverter<T> = class
    class function ToString(Value: T): string; reintroduce;
    class function FromString(const Value: string): T;
  end;
 
 
implementation
uses TypInfo;

{ TEnumConverter<T> }
 
class function TEnumConverter<T>.FromString(const Value: string): T;
var
  Res: Byte;
begin
  Assert(SizeOf(T) = SizeOf(Res), 'Size of source and dest varies in TEnumConverter<T>.FromString');
  Res := GetEnumValue(TypeInfo(T), Value);
  Move(Res, Result, SizeOf(T));
end;
 
class function TEnumConverter<T>.ToString(Value: T): string;
var
  Val: Byte;
begin
  Assert(SizeOf(T) = SizeOf(Val), 'Size of source and dest varies in TEnumConverter<T>.ToString');
  Move(Value, Val, SizeOf(Value));
  Result := GetEnumName(TypeInfo(T), Val);
end;
 
end.

Known limitations

  • The class supports only 1 byte in size enumerated types. In other words, any type with no more than 256 elements, or a ordinality not greater than 255 if explicitly assigned.
  • The class is based on Generics, so it requires Delphi 2009 or newer in order to compile (for now tested only in XE5).

Spanish

Contenido también disponible en Español: Clase genérica para convertir una enumeración en cadena y viceversa

Advertisements

Here I’m, writing in English

This is a kind of introduction and justification as for why am I writing this blog in English.

For those who doesn’t know me, I have to say I’m a native Spanish speaker (You’ll find more in the about jachguate section), and I’m writing here although I’m pretty sure my English is far from perfect, but from time to time I feel the need to reach a broader audience with my code, examples and opinions, and this just couldn’t happen in my native tongue.

I already have a blog in Spanish, named El blog de jachguate. If you read Spanish, I recommend it to you. If you don’t, don’t be shy and take a look at the code and if you got interested on a topic paste the url in Google translator to get a English version of my previous posts.

I’m a bit confident about writing in English since my StackOverflow answers usually get positive feedback and people seems to understand what I want to say. Fortunately I write on technical things, so I look better than if you speak with me about anything else on the street. I’m very open, so feel free to send me corrections and improvements on anything you see it’s wrong in the site.

From now, some of the posts I publish in Spanish will get also into the English Blog, but my goal is not to translate all the content. We’ll see.

Thanks for reading and I hope you enjoy and maybe learn something new from time to time here.

Your comments are welcome.