Reputation: 1089
I am trying to get a better understanding of generics but I am stuck because I want to refactor my code example but it doesn't work and my understanding isn't good enough to see why and how I could fix it:
My example is just for education purpose, so I don't worry about performance or memory leaks etc...
public static void InstanceView<TView, TViewModel>()
where TView : Window
where TViewModel : class, new()
{
var viewToInstance = (TView) Activator.CreateInstance(typeof (TView), new TViewModel());
viewToInstance.ShowDialog();
viewToInstance.Close();
}
public static void InstanceView<TView>()
where TView : Window
{
var viewToInstance = (TView)Activator.CreateInstance(typeof(TView));
viewToInstance.ShowDialog();
viewToInstance.Close();
}
I don't want the redundancy
viewToInstance.ShowDialog();
viewToInstance.Close();
My workaround for the moment is:
private static void displayHandle<T>(T window) where T : Window
{
window.ShowDialog();
window.Close();
}
I call this in both InstanceView implementation instead of ShowDialog() etc.
I have tried something like:
public static void InstanceView<TView>()
where TView : Window
{
InstanceView<TView, null>;
}
But it doesn't work. Is there a way to achieve this ?
PS: I am using Visual Studio 2010
Thank you in advance!
Upvotes: 1
Views: 61
Reputation: 149656
But it doesn't work. Is there a way to achieve this ?
null
is not a type parameter. More specifically in C#, it isn't even a type. Since you have a constraint on TViewModel
to be a reference type with a default constructor, you can pass an object
type to it, or any other reference type that fits the constraints:
public static void InstanceView<TView>()
where TView : Window
{
InstanceView<TView, object>;
}
This will also work:
public class Void { }
public static void InstanceView<TView>()
where TView : Window
{
InstanceView<TView, Void>;
}
Upvotes: 1