Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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();
share|improve this question
    
Don't they have a common interface or base class? –  ChrisWue Oct 23 '13 at 1:26
    
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. –  Sabe Oct 23 '13 at 15:38

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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