Feel like sharing?

Did you know that you can assign the value of an Enum from a different one? Take the follow example:

public enum Roles
{
   Anonymous,
   Employee,
   Manager,
   Admin,
   Super
}

public enum PublicRoles
{
   Employee = Roles.Employee,
   Manager = Roles.Manager,
   Admin = Roles.Admin
}

This seemingly innocent capability allows you to easily manage public views of your Enums or hide Enum values from other services where you only want the subset to be available, and would rather not handle via data validation.

You can cast the enumerations for comparison:

if((Roles)myPublicRole == Roles.Manager)
    Console.Writeline('Selected role is manager');

Another highlight of using Enum subsets is that Automapper handles the conversions automatically as long as the property names are the same. We don’t even have to manually add a .ForMember translation:

using System;
using AutoMapper;

public enum Roles
{
   Anonymous,
   Employee,
   Manager,
   Admin,
   Super
}

public enum PublicRoles
{
   Employee = Roles.Employee,
   Manager = Roles.Manager,
   Admin = Roles.Admin
}
public class Person
{
	public Roles Role { get; set; }
	public string Email { get; set; }
	
}

public class CreatePersonDto
{
	public PublicRoles Role { get; set; }
	public string Email { get; set; }
	
}


public class Program
{
	public static void Main()		
	{
		
		var config = new MapperConfiguration(cfg => { 
			cfg.CreateMap<CreatePersonDto, Person>();																					 
		});
		
		IMapper mapper = config.CreateMapper();
		
				
		var personToCreate = new CreatePersonDto { 
			Email = "whoami@youneedtoask.com",
			Role = PublicRoles.Admin
		};
		
		var createdPerson = mapper.Map<Person>(personToCreate);
		
		Console.WriteLine("Created person: e-mail={0}, role={1}", 
                    createdPerson.Email, createdPerson.Role);
		
	}
}

See the working sample on dotnetfiddle.

I have only used Enum subsets sparingly, mostly in cases where we have some Enum properties that we wanted to hide from the end user and felt the most consistent approach was designing our service layer to receive the subset, rather than filtering the full Enum on the display.

As usual, not rocket science, but hope this little tip helps!

Feel like sharing?

Last modified: June 7, 2020

Author

Comments

Write a Reply or Comment

Your email address will not be published.