Sunday, July 27, 2014

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

Thanks for your response. I am new to WPF/MVVM and not much aware of dependency container like Unity or MEF. But will surely look into it.


Btw, "type" is a parameter of a method. So, you can pass the same as key parameter to dictionary object and execute the delegate method the value of dictionary object pointing to. This (function pointer) works great in my application where I don't have to write lot of if/else to execute specific method.



functions[type](); // Executes ProductsList()

Similarly, what I am looking for is the object/type creator that gives me new object of a type based on the type parameter passed to a dictionary object or a method.



// Instead of the following
if (type = "Products")
this.ViewModel = new ProductsViewModel();
else if (type = "Categories")
this.ViewModel = new CategoriesViewModel();
else if (type = "Customers")
this.ViewModel = new CustomersViewModel();

// I need something like this
this.ViewModel = TypesList[type](); // where TypesList is a dictionary object

// OR like this...

this.ViewModel = TypeCreator(type); // where TypeCreator is a method where type parameter is passed, but then how does that method look like?

I hope that explains well.


Thanks,


Chirag




No comments:

Post a Comment