Option Strict and WebRequest object

  • Thread starter Thread starter Elliot M. Rodriguez
  • Start date Start date
E

Elliot M. Rodriguez

This line raises a precompiler error when Option Strict is turned on:
Dim objRequest As System.Net.HttpWebRequest =
System.Net.HttpWebRequest.Create(m_SearchURL)

The error:

Option Strict On disallows implicit conversions from 'System.Net.WebRequest'
to 'System.Net.HttpWebRequest'.

This is very confusing to me. Why would I need to cast this from WebRequest
if HttpWebRequest is its own object?
 
Elliot M. Rodriguez said:
This line raises a precompiler error when Option Strict is turned
on: Dim objRequest As System.Net.HttpWebRequest =
System.Net.HttpWebRequest.Create(m_SearchURL)

The error:

Option Strict On disallows implicit conversions from
'System.Net.WebRequest' to 'System.Net.HttpWebRequest'.

This is very confusing to me. Why would I need to cast this from
WebRequest if HttpWebRequest is its own object?

"...is it's own object"??

Not every object/class derived from WebRequest is a HttpWebRequest object.
As the docs say, the Create method can either return a HttpWebRequest object
or a FileWebRequest object. If you are not sure which type is returned,
declare objRequest As WebRequest. In addition, you can check the type and
assign the type casted reference to a variable declared as HttpWebRequest or
FileWebRequest, but only if you really need to distinguish because you want
to use specific members. You can skip the check if you are sure that it only
will return one of both types:

objRequest = directcast( _
HttpWebRequest.Create(m_SearchURL), HttpWebRequest _
)
 
Armin:

I need to improve on RTFM before I post. Thank you for clarifying this for
me. I ended up using CType to cast it to an HttpWebRequest object.
 
Elliot M. Rodriguez said:
Armin:

I need to improve on RTFM before I post. Thank you for clarifying
this for me. I ended up using CType to cast it to an HttpWebRequest
object.

Are you sure a HttpWebRequest object is returned? ;-) If you are, DirectCast
is faster.
 
Back
Top