c# property get,set with different types

Timuçin picture Timuçin · Apr 15, 2011 · Viewed 30k times · Source

I have such an enum and a property.

        public enum Type
        {
            Hourly = 1,
            Salary = 2,
            None = 3
        };


        public string EmployeeType
        {
            get
            {
                string type;
                switch (employeeType)
                {
                    case Type.Hourly:
                        type = "Hourly Employee";
                        break;
                    case Type.Salary:
                        type = "Salary Employee";
                        break;
                    default:
                        type = "None";
                        break;
                }
                return type;
            }

            // **EDIT:**
            // Now I am trying to parse the string as enum Type.
            // But Constructor still waits a string to set EmployeeType.
            set
            {
                employeeType = (Type)Enum.Parse(typeof(Type), value);
            }
        }

This is my class:

public class Employee
{
     private Type employeeType;
}

And I want to create such a constructor:

Employee(Employee.Type type) 
{
      EmployeeType = type;
}

EDIT:

Cannot implicitly convert type 'Payroll.Employee.Type' to 'string'

How should I write the set accessor of the property?

UPDATE:

I wanted the get accessor to return string and set accessor to take parameter type Employee.Type. I learned that it is impossible to do this in a property according to the C# spec. I have to write separate getter and setter methods.

Answer

Yuriy Faktorovich picture Yuriy Faktorovich · Apr 15, 2011

Use DescriptionAttribute instead.

public enum Type
{
    [Description("Hourly Employee")]
    Hourly = 1,
    [Description("Salary Employee")]
    Salary = 2,
    [Description("None")]
    None = 3
};

Then you would just have an

public Type EmployeeType {get; set;}

property. And if somebody wanted to write it out, they could get the description. I'd also call it Type instead of EmployeeType, because the call myEmployee.EmployeeType sounds redundant. Your other option might be to unroll the property and have two methods

public string GetEmployeeType() { //your switch statement }
public void SetEmployeeType(EmployeeType type)
{
    _type = type;
}

Not quite as elegant as a property, but quickly does the job. Also remember that properties in IL are just methods.