I am learning C# and was trying different ways to add to list. I tried two different method below . First One does not work, second one does work.
What is wrong with first method?
class Program
{
static void Main(string[] args)
{
Employee emps = new Employee();
emps.PromoteEmp(emps.emp);
}
}
class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public int Experience { get; set; }
public List<Employee> emp;
public Employee()
{
emp = new List<Employee>();
emp.Add(new Employee() { ID = 1, Name = "A", Experience = 6, Salary = 30000 });
emp.Add(new Employee() { ID = 2, Name = "B", Experience = 4, Salary = 10000 });
emp.Add(new Employee() { ID = 1, Name = "C", Experience = 5, Salary = 15000 });
emp.Add(new Employee() { ID = 1, Name = "D", Experience = 8, Salary = 60000 });
}
public void PromoteEmp(List<Employee> empList)
{
foreach (Employee item in empList)
{
if (item.Experience > 5)
{
Console.WriteLine(item.Name + " promoted ");
}
}
}
}
Second Method
class Program
{
static void Main(string[] args)
{
Employee emps = new Employee();
emps.AddToList();
emps.PromoteEmp(emps.emp);
}
}
class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public int Experience { get; set; }
public List<Employee> emp;
public void AddToList()
{
emp = new List<Employee>();
emp.Add(new Employee() { ID = 1, Name = "A", Experience = 6, Salary = 30000 });
emp.Add(new Employee() { ID = 2, Name = "B", Experience = 4, Salary = 10000 });
emp.Add(new Employee() { ID = 1, Name = "C", Experience = 5, Salary = 15000 });
emp.Add(new Employee() { ID = 1, Name = "D", Experience = 8, Salary = 60000 });
}
public void PromoteEmp(List<Employee> empList)
{
foreach (Employee item in empList)
{
if (item.Experience > 5)
{
Console.WriteLine(item.Name + " promoted ");
}
}
}
}
Thank You :)