c# - Instantiate an object in switch statement but cant use it outside of the scope of switch statement -


i have 1 pdf "window sticker" template class can use car dealers 1 dealer wants customize way, not dealers' way.

so, created 2nd pdf "window sticker" template class particular dealer.

then found i'm having trouble instantiating in switch statement particular dealer due scope issues. what's workaround it, or other way it?

public class foo1 {     public foo1() { }     public string generatepdf() { return "red"; } } public class foo2 {     public foo2() { }     public string generatepdf() { return "blue"; } }  object pdftemplate; long dealeraccountid = 121;  //247  switch(dealeraccountid) {    case 247:        pdftemplate = new foo2();        break;    default:        pdftemplate = new foo1();        break; }  string color = pdftemplate.generatepdf(); 

the problem isn't scope. type of pdftemplate variable. object isn't going cut it. should create interface has generatepdf method , use type. else doesn't know possible methods of pdftemplate variable, generatepdf.

public interface igenerator {     string generatepdf(); }  public class foo1 : igenerator {     public foo1() { }     public string generatepdf() { return "red"; } } public class foo2 : igenerator {     public foo2() { }     public string generatepdf() { return "blue"; } }  igenerator pdftemplate; long dealeraccountid = 121;  //247  switch(dealeraccountid) {    case 247:        pdftemplate = new foo2();        break;    default:        pdftemplate = new foo1();        break; }  string color = pdftemplate.generatepdf(); 

for op understand options dynamic, please don't use this.

when using dynamic, try resolve method call on run-time. compiler doesn't warn non-existing method, assume there on run-time (in other words: bugs visible after compiling, , possibly after releasing product). don't need interface though.

dynamic pdftemplate;  ...  string color = pdftemplate.generatepdf(); 

this work, no hassle, working code. (check happens if make typo, generatepdf())


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -