Just starting out and need all the help. The below code won't run. Error msg says "reference not set to the instance of an object", and it points to the employee reference in the WriteLine method. Kindly assist
class Program
{
static void Main(string[] args)
{
List<Employee> empList = new List<Employee>()
{
new Employee { ID = 101, Salary = 6000000, Name = "Jane" },
new Employee{ ID = 102, Salary = 6000000, Name = "Jane" },
new Employee { ID = 103, Salary = 6000000, Name = "James" },
new Employee{ ID = 104, Salary = 6000000, Name = "Jasmie" },
new Employee { ID = 105, Salary = 6000000, Name = "Janet" },
};
Predicate<Employee> emPredicate = new Predicate<Employee>(getEmpName);
Employee employee = empList.Find(emp=> emPredicate(emp));
Console.WriteLine(" ID = {0}, Name = {1}",employee.ID,employee.Name );
Console.ReadLine();
}
public static bool getEmpName(Employee em)
{
return em.ID == 002;
}
}
class Employee
{
public int ID { get; set; }
public int Salary { get; set; }
public string Name { get; set; }
}
If your program throw an exception at runtime then it means it does compile
There is no employee with ID 002. That's why the Find method returns null and you are getting the NullReferenceException.
I would use more appropriate names for my methods. For example getEmpName doesn't return a name it returns a bool, that makes your predicate a bit confusing. You can name it GetEmployeeById and you can add an id parameter to your method then it makes some sense.You can also just use:
Employee employee = empList.Find(emp => emp.ID == 2);
If you just want to find the employee that has the ID 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With