Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert TryCast in c#?

Tags:

c#

asp.net

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.

like image 648
Renu123 Avatar asked Jul 28 '10 07:07

Renu123


2 Answers

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; 
like image 169
Fredrik Mörk Avatar answered Sep 19 '22 13:09

Fredrik Mörk


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.

like image 36
Thorarin Avatar answered Sep 16 '22 13:09

Thorarin