Why is the code in my foreach not available? (An exact copy of the working code that was checked by the module)

The code below is an exact copy of the code that works great. The difference is that this code is placed in the WCF service application project, while the working code is from the Windows Forms application project. The code in foreach is unreachable, which is strange because I have tested the code before and it works by returning the correct values

public IEnumerable<Employee> GetStudentDetails(string username,string password) { var emp = agrDb.LoginAuthentication(username, password);//procedure in the database thats returning two values //Namely: EmployeeFirstName and EmployeeLastName List<Employee> trainerList = new List<Employee>(); foreach (var item in emp) { //unreachable code here Employee employ = new Employee(); employ.EmployeeFirstName = item.EmployeeFirstName; employ.EmployeeLastName = item.EmployeeLastName; trainerList.Add(employ); //trainerList.Add(item.EmployeeLastName); } return trainerList; } 
+4
source share
3 answers

The code inside foreach loops may not be available if the array or collection is not initialized before execution.

 List<Employee> emp; // Run when program starts, called from Program.cs private void InitialiseApplication() { emp = new List<Employee>; // Gather data for employees from... somewhere. DataAccess.GetEmployees(emp); } private void DoStuff() { foreach (var item in emp) { // Do something. } } 

The above code will return a warning because "emp" is not initialized during development.

I got the same warning in my code at different stages, including inside the constructors. However, the flow of execution is not affected, because by then "emp" is initialized.

This can happen with your code. Check where and when "emp" is initialized during program flow. You may need to β€œjoin” the program to achieve this, if this is not obvious in appearance.

+6
source

Perhaps you always return a new empty array in agrDB.LoginAuthentication() , and your IDE knows that the foreach loop will never agrDB.LoginAuthentication() over any elements.

0
source

The code is available, but if it does not execute, it means that emp empty. You should check if the username and password value that you are using agrDb.LoginAuthentication(username, password) and that agrDb.LoginAuthentication(username, password) returns the value.

0
source

Source: https://habr.com/ru/post/1442024/


All Articles