-1

I am trying to cast a class that inherits WebRequest to HttWebRequest (since I cannot inherit HttpWebRequest directly) but I get that the cast is not valid. Any idea how I can get a HttpWebRequest from my instance?

This is the code:

static void Main(string[] args)
    {

        WebRequest wr = new WR("bla");
        HttpWebResponse webres = (HttpWebResponse) wr; // this fails
        Console.ReadKey();
    }

    public class WR : WebRequest
    {
        private string bla;
        private Uri url;

        public WR(string x)
        {
            bla = x;
        }

        public override Uri RequestUri
        {
            get { return this.url; }
        }
    }
Cyan
  • 1,068
  • 1
  • 12
  • 31
  • That's because WebRequest does not inherit HttpWebRequest, but HttpWebRequest inherits WebRequest. Change "WebRequest" to "HttpWebRequest". To give an example. Ex. you have a base class named "Human" which you inherit from a class named "Boy". However you can a class named "Girl" too which inherits "Human". Neither "Boy" or "Girl" can convert to each other. Since they're both "Human", but not the same. – Bauss Mar 06 '15 at 19:18
  • Note that you'd normally get a `WebResponse` (or `HttpWebResponse`) by calling `.GetResponse()` on the original `WebRequest` object. Certainly not by casting a request to a response. – James Thorpe Mar 06 '15 at 19:20
  • What do you really want to achieve? Why do you need your own `WebRequest` derived class? Why not use standard facilities? Or encapsulate `WebRequest` - `WebResponse` stuff inside some custom class? – Eugene Podskal Mar 06 '15 at 19:21
  • I'm trying to mock a WebRequest. – Cyan Mar 06 '15 at 19:22
  • 1
    Have you seen [this question](http://stackoverflow.com/questions/87200/mocking-webresponses-from-a-webrequest)? – James Thorpe Mar 06 '15 at 19:24

2 Answers2

0

Heritage simply cannot work this way. HttpWebRequest is a more specific version of WebRequest. Since you only inherit from WebRequest, your object cannot satisfy HttpWebRequest.

If you do need some fields from HttpWebRequest try composition instead of heritage. Depending on your needs, you could make some class that basically possesses a HttpWebRequest field along your WR fields and function.

Note: This answer takes in account you cannot inherit from HttpWebRequest as you stated. I dont know why. If for some reason you realise you CAN inherit from HttpWebRequest, you should.

-1

what you need to write is....

HttpWebResponse webres = new HttpWebResponse();