DaveDev
DaveDev

Reputation: 42175

Help With Generics? How to Define Generic Method?

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

Upvotes: 0

Views: 463

Answers (2)

Josiah
Josiah

Reputation: 3332

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
}

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273199

Yes you can write this generic extension method. But since it does not use any of its type-parameters in the function signature, you will always have to specify the types. That means you cannot use:

 string r = helper.GenerateWidget(modelData);

but you will always need:

 string r = helper.GenerateWidget<SpecificHtmlGenerator, SpecificWidget>(modelData);

Upvotes: 2

Related Questions