How to create objects dynamically by passing type in c#?


currently, have following code:

if (type = "products")  	this.viewmodel = new productsviewmodel();  else if (type = "categories")  	this.viewmodel = new categoriesviewmodel();  else if (type = "customers")  	this.viewmodel = new customersviewmodel();  


now, want simplify 1 , create objects based on type parameter passed, if there 40 or 50 different types, don't have type in many if/else statements. there easy way out similar delegates or function pointers? 

for example, have function pointers/delegates defined based on type , can execute respective function passing key dictionary type.

dictionary<string, func<string, list<string>>> functions = new dictionary<string, func<string, list<string>>>();    functions.add("products", productslist);  functions.add("customers", customerslist);  functions.add("categories", categorieslist);    functions["products"](); 	// executes productslist() function  

thanks in advance

chirag

if view model classes implements same interface or base class, can use dictionary, e.g.:

    class baseviewmodel { }      class productsviewmodel : baseviewmodel { }     class categoriesviewmodel : baseviewmodel { }     class customersviewmodel : baseviewmodel { }
            dictionary<string, baseviewmodel> typeslist = new dictionary<string, baseviewmodel>();             typeslist.add("products", new productsviewmodel());             typeslist.add("categories", new categoriesviewmodel());             typeslist.add("customers", new customersviewmodel());              string type = "products";             baseviewmodel viewmodel = typeslist[type]; 




Visual Studio Languages  ,  .NET Framework  >  Visual C#



Comments

Popular posts from this blog

Azure DocumentDB Owner resource does not exist

job syspolicy_purge_history job fail in sqlserver 2008

Trying to register with public marketplace error with 'Get-AzureStackStampInformation'