3

Below I am providing two examples of converting a dynamic array of some data to a variant. In first example array holds Integers, in second example array holds TMyEnums.

I would think that both examples are pretty simmilar, however, the second example returns an error "Invalid variant type conversion" during runtime.

program Project128;

{$APPTYPE CONSOLE}

uses
  SysUtils, Variants;

type
  TIntegerArray = array of Integer;

type
  TMyEnum = (meOne, meTwo, meFour, meTen);
  TMyEnumArray = array of TMyEnum;

var
  LVar1, LVar2: Variant;
  LIntArray : TIntegerArray;
  LMyEnumArray: TMyEnumArray;
begin
  SetLength(LIntArray, 2);
  DynArrayToVariant(LVar1, LIntArray, TypeInfo(TIntegerArray)); //Works

  SetLength(LMyEnumArray, 2);
  DynArrayToVariant(LVar2, LMyEnumArray, TypeInfo(TMyEnumArray)); //Invalid variant type conversion
end.

Is it possible to convert array of enums to a variant? I know that I could use array of integers and cast them back to enums but I do not want to do this.

Wodzu
  • 6,932
  • 10
  • 65
  • 105
  • What var type are you hoping the elements to be stored as? If you push a `TMyEnum` scalar into a variant it will be `varByte`. Do you want a variant array of `varByte`. `DynArrayToVariant` will never do what you want so you'll have to code in manually. – David Heffernan Feb 10 '15 at 11:28
  • Ok, if it is not possible that is fine. Just wanted to know that. Is this code safe (will always work) `DynArrayToVariant(LVar2, LMyEnumArray, TypeInfo(TByteArray))` assuming that all my enums are in 0-255 range? – Wodzu Feb 10 '15 at 14:35
  • I think that will be fine. Because byte is a type that is directly supported in a variant – David Heffernan Feb 10 '15 at 14:39
  • I guess this is not what you are searching for but, have you considered to store/retrieve the elements as `strings`? You can do this by using `GetEnumName` and `GetEnumValue`. – Guillem Vicens Feb 10 '15 at 15:08
  • @GuillemVicens Thanks for the tip, I've tried the approach you suggested but unfortunately it will not work for discontiguous enumerations and I have to deal with them too. – Wodzu Feb 10 '15 at 16:08
  • ah yes, discontinous enumeration get no type info generated :-(. Anyway, you might want to consider using "padding" as suggested in the accepted answer to this [question](http://stackoverflow.com/questions/1420562/why-do-i-get-type-has-no-typeinfo-error-with-an-enum-type). That way you could use `GetEnumName` and `GetEnumValue`. Granted, not the most elegant solution but better as nothing. – Guillem Vicens Feb 10 '15 at 16:23
  • Yeah, I saw the question you meantion. The problem is that my colleague add to the enums one with value = 91 :) it means we would have to pad like 80 values... Anyway, thanks for your interest Guillem :) – Wodzu Feb 11 '15 at 07:04

0 Answers0