How to convert following vb code in to c#?
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
I tried it using AS
operator in c# but it is not working.
You can cast using as
; this will not throw any exception, but return null
if the cast is not possible (just like TryCast
):
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
The as
operator is in fact the C# equivalent:
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; Debug.Assert(request != null); // request will be null if the cast fails
However, a regular cast is probably preferable:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
WebRequest.Create
should always result in a HttpWebRequest when called with a specific URI scheme. If there is nothing useful to do when the cast fails, then there is no need to defensively cast the variable. If you don't care about the protocol used, then your request
variable should be of type WebRequest
(but you lose the ability to check HTTP status codes).
To complete the picture about casts and type checking in C#, you might want to read up on the is
operator as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With