views:

3546

answers:

2

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?

+21  A: 

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 is 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.

Ch00k
+1, you beat me to it.
x0n
This is right. It would have been nice if there was a way to get a HttpWebRequest from either HttpWebRequest.Create or something like HttpWebRequest.CreateHttp without casting. The first would be something like public new static HttpWebRequest Create(string url). Either way, if the url wasn't HTTP(s), it should just throw some InvalidArgumentException.
Matthew Flaschen
A very nice explanation of a very strange design decision (dare I say wrong?) by the .NET creators.
I. J. Kennedy
+1  A: 

WebRequest is an anstract class which has a factory method Create that depending on the URL passed in creates an instance of a concrete subclass. Whether you need or want HttpWebRequest httpreq = (HttpWebRequest)WebRequest.Create(strUrl); instead of WebRequest req = WebRequest.Create(strUrl); depends on your needs and on what kind of URLs you pass in. If you only pass in HTTP: URLs then the former allows you to access the properties and methods the subclass HttpWebRequest implements in addition to those defined on the base class WebRequest. But if you passed in a FTP: URL then the attempt to cast to HttpWebRequest would fail. The latter is generic and won't fail on any of the types of supported URLs but of course without casting to any subclass you can only access the properties and methods the base class defines.

--

via Martin Honnen

drorhan