C# HttpWebRequest vs WebRequest

Viewed 87369

I saw this piece of code:

var request = (HttpWebRequest) WebRequest.Create("http://www.google.com");

Why do you need to cast (HttpWebRequest)? Why not just use HttpWebRequest.Create? And why does HttpWebRequest.Create make a WebRequest, not a HttpWebRequest?

4 Answers

The Create method is static, and exists only on WebRequest. Calling it as HttpWebRequest.Create might look different, but its actually compiled down to calling WebRequest.Create. It only appears to be on HttpWebRequest because of inheritance.

The Create method internally, uses the factory pattern to do the actual creation of objects, based on the Uri you pass in to it. You could actually get back other objects, like a FtpWebRequest or FileWebRequest, depending on the Uri.

We will be using WebRequest method because it will work as generic method for transparently retriving file from

  • Web servers,
  • FTP servers and
  • File server

So

var httpRequest = WebRequest.Create("http://somedomain.com");       // return an instance of type(HttpWebRequest)
var ftpRequest = WebRequest.Create("ftp://ftp.somedomain.com");     // return an instance of type(FtpWebRequest)
var fileRequest = WebRequest.Create("file://files.somedomain.com"); // return an instance of type(FileWebRequest)

Return Type of all three methods (HttpWebRequest, FtpWebRequest, FileWebRequest) all drive from base class WebRequest which is return type of WebRequest.Create(string). Now which subclass to instantiate is determined using the protocol prefixes (http:, https:, ftp:, file:)

So, any URI string (with any of these four prefixes) you pass to the Create method will be transparently handled by the WebRequest base class so you don't even have to know specifically what sub-class was returned

Related