'C# HttpWebRequest vs WebRequest
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?
Solution 1:[1]
WebRequest is an abstract 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: URL's, then the former code 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 URL's but of course without casting to any subclass you can only access the properties and methods the base class defines.
-- via Martin Honnen
Solution 2:[2]
The cast is only necessary when you need access to members unique to HttpWebRequest. The idea is that if the properties/methods supported on WebRequest are sufficient, then you can write an application that will work against many types of request/response protocols. In this case the URI could be something given by the user using any protocol supported by pluggable protocols. New protocols can even be supported without altering the original software.
If your application needs more control over features specific to a particular protocol then you can restrict requestUri to your supported scheme(s) and cast WebRequest to the appropriate protocol-specific subclass. This limits the protocols supported by your application, but enables you to tweak protocol-specific features.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SteveC |
| Solution 2 |
