Reputation: 4661
I have a extension method for an enum
public static IEnumerable<T> GetFlags<T>(this T value) where T : struct
{
CheckIsEnum<T>(true);
foreach (T flag in Enum.GetValues(typeof(T)).Cast<T>())
{
if (value.IsFlagSet(flag))
yield return flag;
}
}
I try to get the result like this:
Zone_Status_ZoneConditionFlagEnum flags = (Zone_Status_ZoneConditionFlagEnum)flagsRaw;
List<Zone_Status_ZoneConditionFlagEnum> ZoneConditionFlags_List = (List<Zone_Status_ZoneConditionFlagEnum>)flags.GetFlags();
But I get
NX584(NX584Test)->Error parsing message: Cannot implicitly convert type [Digicom.NX584Engine.Messages.Zone_Status_ZoneConditionFlagEnum] to System.Collections.Generic.List`1[Digicom.NX584Engine.Messages.Zone_Status_ZoneConditionFlagEnum].
Upvotes: 2
Views: 330
Reputation: 1062512
The first issue here is that a sequence is different to a list; if you need a list, either return a list, or add .ToList()
after GetFlags()
, i.e.
var ZoneConditionFlags_List = flags.GetFlags().ToList();
However, the bigger problem is that you can't use that IsFlagSet
in that generic context; that method is not defined for an arbitrary T : struct
.
Personally, I think you'd be better just to treat it as a [Flags]
enum throughout; I assume you have existing code that wants a list rather than a single value?
Upvotes: 1
Reputation: 391276
GetFlags
returns an IEnumerable<T>
, not a List<T>
, you cannot cast here.
You should, however, be able to construct a list from the results:
List<Zone_Status_ZoneConditionFlagEnum> ZoneConditionFlags_List = flags.GetFlags().ToList();
However, the error does not match the code here exactly, it should complain about an IEnumerable not be able to be cast, but instead it says the enum type. Are you sure this is the right code?
Upvotes: 0
Reputation: 1499790
It's not clear to me why you're getting that error - but you can't cast the result of GetFlags<T>
to a List<T>
, because it doesn't return a List<T>
. The simplest fix would be:
var ZoneConditionFlags_List = flags.GetFlags().ToList();
If that doesn't work, please give the new error message.
Alternatively, you could change GetFlags
so it actually returned a List<T>
rather than using an iterator block.
Upvotes: 2