C# HttpWebRequest vs WebRequest

Unknown picture Unknown · May 22, 2009 · Viewed 83.7k times · Source

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?

Answer

David Wengier picture David Wengier · May 22, 2009

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.