GoldBishop
GoldBishop

Reputation: 2861

Writing extension for HttpResponse & HttpResponseBase

I have a situation where i would like to write an extension that can be consumed both on HttpResponse & HttpResponseBase.

After some research, found that both are siblings but only by simple extension of the Object class.

And since you can only define a Generic with one specific class i am running into a problem of having to write the same method twice to handle two different object models: Web application redirects and MVC redirects.

Current implementation, although i dont like it:

public static void RedirectTo404(this HttpResponseBase response)
{
    response.Redirect("~/404.aspx");
}
public static void RedirectTo404(this HttpResponse response)
{
    response.Redirect("~/404.aspx");
}

I would like to have something like this (i know its not syntactically possible, but to give an idea)

public static void RedirectTo404<T>(this T response) where T : HttpResponseBase , HttpResponse
{
    response.Redirect("~/404.aspx");
}

Upvotes: 1

Views: 3692

Answers (1)

usr
usr

Reputation: 171246

Have the HttpResponse version delegate to the HttpResponseBase version by invoking it with new HttpResponseWrapper(response). That saves you duplicating the code body.

Or have a common method taking a parameter of type dynamic. I would not choose this method though because it is dynamically typed for no good reason.

public static void RedirectTo404(this HttpResponseBase response)
{
    response.Redirect("~/404.aspx");
}
public static void RedirectTo404(this HttpResponse response)
{
    RedirectTo404(new HttpResponseWrapper(response)); //delegate to implementation
}

Upvotes: 5

Related Questions