views:

91

answers:

1

Is it possible to create a generic method with a definition similar to:

public static string GenerateWidget<TypeOfHtmlGen, WidgetType>(this HtmlHelper htmlHelper
                                           , object modelData) 

// TypeOfHtmlGenerator is a type that creates custom Html tags. 
// GenerateWidget creates custom Html tags which contains Html representing the Widget.

I can use this method to create any kind of widget contained within any kind of Html tag.

Thanks

+1  A: 

There's a few improvements you might want to add, because it looks like you're going to have to instanciate those classes within your method:

public static string GenerateWidget<TypeOfHtmlGen, WidgetType>(this HtmlHelper htmlHelper
                                           , object modelData)
    where TypeOfHtmlGen: new()
    where WidgetType: new()
{
    // Awesome stuff
}

Also, you're probably going to want the widget and html gen to implment some sort of interface or base class:

public static string GenerateWidget<TypeOfHtmlGen, WidgetType>(this HtmlHelper htmlHelper
                                           , object modelData)
    where TypeOfHtmlGen: HtmlGenBaseClass, new()
    where WidgetType: WidgetBaseClass, new()
{
    // Awesome stuff
}
Josiah
I understand that you can specify a constraint using syntax similar to `where TypeOfHtmlGen: new()`, but I am unsure what `new()` means. Can you explain that bit please? Thanks
DaveDev
From MSDN: The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. Apply this constraint to a type parameter when your generic class creates new instances of the type. http://msdn.microsoft.com/en-us/library/sd2w2ew5(VS.80).aspx
Scott J