Reputation: 704
I'm trying to create a Dictionary which has a generic Enum type as the key, this is how my class looks:
public class Error : IError
{
public StatusEnum Status { get; set; }
public Dictionary<Enum, string> Errors { get; set; }
public Error(StatusEnum status, Dictionary<Enum, string> errors)
{
Status = status;
Errors = errors;
}
}
And I have an enum class like so:
public enum IdentityErrorEnum
{
PasswordRequiresDigit,
PasswordRequiresLower,
PasswordRequiresNonAlphanumeric,
PasswordRequiresUpper,
PasswordTooShort
}
An EnumHelper
which converts a string to an enum:
public static class EnumHelper
{
public static T FromString<T>(string value)
{
return (T)Enum.Parse(typeof(T), value);
}
}
Finally, I'm trying to convert the collection of errors into a Dictionary<Enum, string>
like this where result is an IdentityResult
:
var result = await base.CreateAsync(_userMapper.ToEntity(user), password);
Dictionary<Enum, string> dictionary = result.Errors.ToDictionary(e => EnumHelper.FromString<IdentityErrorEnum>(e.Code), e => e.Description);
But this gives a build error which says:
Cannot implicitly convert type 'System.Collections.Generic.Dictionary<IdentityErrorEnum, string>' to 'System.Collections.Generic.Dictionary<System.Enum, string>'
Upvotes: 0
Views: 215
Reputation: 33823
Your assignment is to a variable of type Dictionary<Enum, string> dictionary
, but what you are returning from your .ToDictionary
call is Dictionary<IdentityErrorEnum, string>
. You just need to update your variable declaration or use var.
Dictionary<IdentityErrorEnum, string> dictionary = result.Errors.ToDictionary(
e => EnumHelper.FromString<IdentityErrorEnum>(e.Code),
e => e.Description);
If in turn you want your dictionary to contain multiple enums (even though your .ToDictionary() call doesn't express this currently), you would need to cast back to enum.
Dictionary<Enum, string> dictionary = result.Errors.ToDictionary(
e => (Enum)EnumHelper.FromString<IdentityErrorEnum>(e.Code),
e => e.Description);
Upvotes: 1