0

I want to create a class named Employee in C#. It needs to have 2 strings containing first and last names and a List property that will contain previous job positions. All 3 properties should be populated through a constructor and unchangeable afterwards.

class Employee
{
    public string firstName { get; }
    public string lastName{ get; }
    private List<string> prevPositions;
    public Employee () {}
    public Employee (string fName, string lName, List<string> pPos)
    {
        firstName = fName;
        lastName = lName;
        prevPositions = pPos;
    }
    public IList<string> Positions
    { get {return prevPos;} }
}

However in my main method I can still use something like:

Employee fEmp = new Employee("John", "Doe", new List<string> { "junior", "senior" });
fEmp.Position.Add("CEO");
foreach (string st in fEmp.Positions)
    Console.WriteLine("Prev Positons are {0}", st);

And I get CEO as part of previous positions. Now I understand that this happens, due to fEmp.Position being a reference to a memory where list is stored, and thus I can use .Add to add element to the list, and my immutability goes to thrash.

Does anyone know how would I go about this?

Tevagu
  • 1
  • Set your properties to readonly – Laurent Lequenne Jul 11 '17 at 13:56
  • 1
    @LaurentLequenne they are readonly because he only has a getter but you can add through the property – Jordy van Eijk Jul 11 '17 at 13:57
  • Euh yah... I'm stupid...and even if your list is readonly, you can still add some items in it :) – Laurent Lequenne Jul 11 '17 at 13:58
  • Not sure but you could try : private readonly string[] prevPositions; – Laurent Lequenne Jul 11 '17 at 14:00
  • @HimBromBeere how about going the duplicate chain one step further (https://stackoverflow.com/questions/4680035/read-only-list-in-c-sharp) instead of marking as duplicate of a duplicate. I know most problems are solvable by adding another layer of indirection, but this awesome knowledge is not meant for problems that are already solved without the extra indirection :P – grek40 Jul 11 '17 at 14:29

0 Answers0