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; }
}
From List<T>.Find
:
Return Value Type: T
The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T.
It isn't finding a match, hence returning default(T)
, which is null
. Add a nullity before Console.WriteLine
, and of course, correct your getEmpName
predicate (I'm assuming you ment to check em.ID == 102
):
if (employee != null)
{
Console.WriteLine(" ID = {0}, Name = {1}",employee.ID,employee.Name );
}