Danny Watson
Danny Watson

Reputation: 165

Using an array in a List - OOP - Generic List

I have created a list:

List<Employee> employees = new List<Employee();

I would like to achieve this:

Employee e1 = new Employee(Job.Employee, "Name", "C Sharp", "Oracle", "SQL");

I currently have this:

Employee e1 = new Employee(Job.Employee, "Name", Skills.CSharp);

This is the code inside the Employee class

public enum Job { Employee, Supervisor, Administrator };
public enum Skills {CSharp, SQL, PHP, Javascript, Web, Python, Oracle, CPlus, Perl };

protected Job job;
protected String employeeName;
protected String employeeName;

public Job Job
{
    get { return job; }
    protected set { job = value; }
}

public String EmployeeName
{
    get { return employeeName; }
    protected set { employeeName = value; }
}

public Skills Skills
{
    get {return skills; } 
}

I want to be able to enter as many 'skills' as I want as currently, only one skill can be entered in the Employee e1 as I have used a enum.

How would I put an array of 'skills' in the list/constructor?

Upvotes: 1

Views: 176

Answers (2)

Jakub Lortz
Jakub Lortz

Reputation: 14896

You can use a params array parameter to pass variable number of Skills parameters to the constructor:

public Employee(Job job, string name, params Skills[] skills)

You will also have to modify the skills field to hold a collection of Skills instead of a single one. You can make it an array if you will not add/remove skills after the employee is created, or an IList<Skills> if you need to modify the collection.

For example:

public class Employee
{
    private List<Skills> _skills;       // skills stored as a private List 
                                        // to allow modification inside Employee class

    public Employee(Job job, string name, params Skills[] skills)
    {
        _skills = new List<Skills>(skills);
        ...
    }

    public IReadOnlyList<Skills> Skills // publicly visible as a read-only list
    {
        get { return _skills.AsReadOnly(); }
    }

    ...
}

Upvotes: 6

clcto
clcto

Reputation: 9648

An alternative to passing in a Skills[], you can change your enum to be a bit-mask of the skills that an employee has:

[Flags]
enum Skills
{
   None = 0,
   CSharp = 1 << 0,
   SQL = 1 << 1,
   PHP = 1 << 2,
   Javascript = 1 << 3,
   ...
}

Then the individual skills can be bitwise ORed together to create the skills that an individual employee has:

Employee e1 = new Employee(Job.Employee, "Name", Skills.CSharp | Skills.SQL | Skills.PHP );

Then to check if an employee has a specific skill, you can use Enum.HasFlag method, eg:

if( e1.Skills.HasFlag( Skills.CSharp ) )

Upvotes: 3

Related Questions