Search code examples
c#.nethttpwebrequestwebrequestsystem.net.httpwebrequest

HttpWebRequest collection Initializer C#


When using HttpWebRequest via HttpWebRequest.Create(url) is there an easier way than the following to initialize a HttpWebRequest by using a object initializer:

class RequestLight
{
    public HttpWebRequest WebRequestObj;

    public RequestLight(string url)
    {
        WebRequestObj = HttpWebRequest.CreateHttp(url);
    }

}

Now this can be used like so (desired effect of object initializer for webreq object)

var obj = new RequestLight("http://google.com") 
                { WebRequestObj = { CookieContainer = null } }.WebRequestObj;

Am I missing something? Or is this the easiest way to get the desired effect?

Note: Using the original way you have to set create the object via a static method then assign each property one by one.


Solution

  • It sounds like you're looking for a way to initialize the request in a single statement - otherwise just using two statements is simpler.

    There's a reasonably simple alternative to this, using a lambda expression - although it's pretty nasty...

    public static class Extensions
    {
        public static T Initialize<T>(this T value, Action<T> initializer) where T : class
        {
            initializer(value);
            return value;
        }
    }
    

    And call it with:

    var request = WebRequest.CreateHttp(uri)
        .Initialize(x => x.CookieContainer = null);
    

    Or for multiple properties:

    var request = WebRequest.CreateHttp(uri).Initialize(x => {
        x.CookieContainer = null;
        x.Date = DateTime.UtcNow;
    });