Question

How to convert TryCast in c#?

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.

 45  71276  45
1 Jan 1970

Solution

 89

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;
2010-07-28

Solution

 13

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.

2010-07-28