Search code examples
c#enumsderived-class

C# limit options of enum in a derived class


So I'm trying to limit the options ,of an enum I declared in the base class, I can select in the derived class.

namespace FLYNET.Personeel
{
    public enum Graad
    {
        Captain,
        SeniorFlightOfficer,
        SecondOfficer,
        JuniorFlightOfficer,
        Steward,
        Purser
    };

public abstract class VliegendPersoneelslid : Personeelslid
{
    public VliegendPersoneelslid()
    {
    }

    public override decimal BerekenTotaleKostprijsPerDag()
    {
        return BasisKostprijsPerDag;
    }

    public List<Certificaat> Certificaten { get; set; }
}

The above is the enum I'm trying to use from the base class Staff. In the derived class Cabincrew I want to limit the options that can be selected in the constructor. If the wrong option is selected, it needs to throw a specified exception, so a bit like this :

namespace FLYNET.Personeel
{
    public class CockpitPersoneel : VliegendPersoneelslid
    {
        public int VliegUren { get; set; }

        public Graad Graad { get; set; }


            public CockpitPersoneel()
            {
                if (Grade = Graad.Steward || Grade = Graad.Purser)
                {
                    throw new Exception 
                }
            }

            public override decimal BerekenTotaleKostprijsPerDag()
            {
                decimal kostprijsPersoneel = 0m;
                decimal percentage;

                return kostprijsPersoneel;
            }
        }
    }

I'm aware this is probably a beginners question (and it is :p) but please bear with me.


Solution

  • I suggest using extension methods in order to hide options

    public enum Grade {
       None, // <- zero option is often a good idea to include 
       Captain,
       SeniorFlightOfficer,
       SecondOfficer,
       JuniorFlightOfficer,
       Steward,
       Purser };
    
    public static class GradeExtensions { 
      public static bool IsCabinCrue(this Grade grade) {
        return grade == Grade.Steward || grade == Grade.Purser;
      }
    
      public static bool IsCockpitPersonnel(this Grade grade) {
        return grade == Grade.Captain || 
               grade == Grade.SeniorFlightOfficer ||
               grade == Grade.SecondOfficer ||
               grade == Grade.JuniorFlightOfficer;
      } 
    }  
    

    Then you can use extension methods as if their are methods of the enum when validating Grade values provided:

    public class CabinCrue {
      ...
      public CabinCrue(Grade grade) {
        // Validation: Cabin Crue grade only
        // not Exception but ArgumentException: it's argument grade that's wrong
        if (!grade.IsCabinCrue()) 
          throw new ArgumentException("Cabin crue only", "grade");
    
        Grade = grade;
    
        ...
      } 
    
      public Grade Grade {
        get;
        private set;
      }
      ...
    }