Learning Learning - 10 months ago 41
C# Question

How to return 2 values from single methods and set 2 parent class property calling function 1 time?

I have class like below:

public class Employee
public int EmployeeId { get; set; }
public string Name { get; set; }
public bool performance { get; set; }
public List<Skills> Skills { get; set; }

public class Skills
public int Id { get; set; }
public string skills { get; set; }
public int Rate { get; set; }
public int statistics { get; set; }

I have 2 static methods in which 1st static is responsible to just add list of skills.now for each employee i want to set performance property value which 2nd static method will throw along with list of skills.

I have some logics through which i know that when to return false to performance properties and when to set Rate and Statictics to
0 but the only thing i am not getting is how to i return list of skills and associated true or false value without being calling my 2nd static method


public static List<Employee> ReturnEmployeeList(List<EmployeesModel> employeesModel)
var list = new List<Employee>();
foreach (var item in employeesModel)
new Employee
EmployeeId = item.EmployeeId,
Version = item.Name,
performance=????, // i want to set this value based on value return by 2nd static method
Skills = ReturnSkillList(item.SkillModels)

return list;

private static List<Skills> ReturnSkillList(List<SkillModels> skillModel)
var list = new List<Skills>();
//Here i have some logic in which i know when to set Rate and statictics to 0 and return false for performance properties
return list;

Can anybody please help me with this?

Answer Source

I have a feeling that if you would show the logic behind your code it would be possible to refactor it to a state in which a multi valued return type would not be needed - but I'll answer assuming that this is not relevant.

Three possibilities come to mind, none of which is very pretty in my opinion:

  • out variable:

    bool performance;
    Skills = ReturnSkillList(item.SkillModels, out performance);

    and the function signature is:

     private static List<Skills> ReturnSkillList(List<SkillModels> skillModel, out bool perf)
  • Tuple:

    Tuple<List<Skills, bool> temp = ReturnSkillList(item.SkillModels, out performance);
    Skills = temp.Item1;
    performance = temp.Item2;

    and the function signature is:

     private static Tuple<List<Skills>, bool> ReturnSkillList(List<SkillModels> skillModel, out bool perf)
  • Dedicated class: Create a simple class with the two relevant properties.