1
\$\begingroup\$

I am pushing an Excel file to the server and then reading it's contents. XLS and XLSX files need to be read differently, but the DLL that I'm using has the EXACT same function calls for both types. If I use a 'dynamic' type, I can save a lot of lines of code and avoid redundancy. However, I've been told many times before to avoid using dynamic if possible. Is this a good place to use it?

dynamic excelFile; // is this a good use of dynamic?
switch (fileExtension)
{
    case "xls":
        excelFile = new Excel2007();
        break;
    case "xlsx":
        excelFile = new Excel();
        break;
    default:
        results.Message = string.Format("{0} is of an unrecognized format.", uploadFile.FileName);
        return RedirectToAction("ImportWizard");
}

excelFile.OpenDatabase(targetPath, new FieldData());
excelFile.CurrentTable = excelFile.Tables[0];

var excelRecords = excelFile.ReadRecords(100);
excelFile.CloseDatabase();
\$\endgroup\$
  • \$\begingroup\$ Don't they have a common interface or base class? \$\endgroup\$ – ChrisWue Oct 23 '13 at 1:26
  • \$\begingroup\$ Not at this stage (wasn't sure if that was really needed), but if dynamic isn't a good choice here than I can implement that. \$\endgroup\$ – Sabe Oct 23 '13 at 15:38
2
\$\begingroup\$

The prevalent answer is: No. (Funny enough, working with Office files seems to be a valid exception to the rule).

The problem is that you don't have type validation anymore, and any issues will reveal themselves at run time.

I'd say, if it's a small thing and it won't be touched or changed by people who might not know how it works, go for it (Even then, make sure you document this).

Otherwise, an Interface approach sounds like a better idea, like ChrisWue's comment said.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.