lundi 30 décembre 2019

How to assign values of different types to a variable inside if statements and then use this variable after the if statements?

I am retrieving different types of documents from database, and assigning the received data to the variable items. Different methods are used to retrieve different document types, hence the need for if statements. I cannot initialize items before the if statements, because I don't know beforehand what type of document the user is retrieving. The problem is that I therefore cannot use items after the relevant īf statement has been executed. How to solve this issue? A simplified method:

public ActionResult ExportToExcel()
{
  ...
  if (request.docType == "docType1")
  {  
    var items = _provider.GetDocumentsOfType1(request);
  }
  else if (request.docType == "docType2")
  {
    var items = _provider.GetDocumentsOfType2(request);
  }
  else if ...

}

After retrieving the data, I would need to do some formatting based on what data is in the items variable, and of course return the data. It seems that the only viable thing is to replace the if statements with separate methods, and call the formatting etc. methods from there. But can it all be done within a single method?

Aucun commentaire:

Enregistrer un commentaire