Generic View Models in Silverlight

I like using Base-Classes for any kind of “Class-Group”. Very prominent groups are Models and ViewModels in Silverlight-Applications.

The ViewModel-Baseclass can hold any functionality, that applies to every ViewModel inheriting from it and, if we are talking about Generics, can be very convenient to use.

For example, if I want to apply the factory-pattern to my ViewModels and want every Model to have a static Create-Method I can simply implement this Method in the Base-Class.

public class ViewModelBase 
{ 
	public virtual ViewModelBase Create() 
	{ 
		return new ViewModelBase(); 
	} 
} 

Of cause, without Generics we are limited to the return-Type. We could now override this method in every specific ViewModel to at least return the right ancestor of ViewModelBase. An easier way is, to use Generics for this case. The class could look like this :

public class ViewModelBase where TViewModel : ViewModelBase 
{ 
	public virtual TViewModel Create() 
	{ 
		return Activator.CreateInstance(typeof(TViewModel)); 
	} 
} 

Now we can simply create our new specific ViewModel like this

public class MyViewModel : ViewModelBase

to get what we want generically.

 

Another possible scenario would be the following. We know, every ViewModel contains a Collection of Models, all inheriting from a class called ModelBase. we could extend out code the following way:

public class ViewModelBase where TViewModel : ViewModelBase 
{ 
	public virtual TViewModel Create() 
	{ 
		return Activator.CreateInstance(typeof(TViewModel)); 
	} 
	
	public List MyList {get;set;} 
} 

or, the better way, we could extend our Generic header to be type safe.

public class ViewModelBase 	
                                        where TViewModel : ViewModelBase 
					where TChildModel : ModelBase 
{ 
	public virtual TViewModel Create() 
	{ 
		return Activator.CreateInstance(typeof(TViewModel)); 
	} 

	public List MyList {get;set;} 
} 

Defining a Class by

public class MyViewModel : ViewModelBase

Like always, if we talk about inheritance, you should avoid to go too far with that. I implemented a Framework I use for rapid prototyping where a lot of things are done in the base-class via reflection, but in a productive environment its not always what you want. Plan your development as precise as possible.

  • What do you want to be individually implemented by each ViewModel ?
  • When is it a good thing to implement it in the Base-Class ?
  • How confusing is you inheritance for other developers ?

 

Good Luck 😮