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?