开发者

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 开发者_JAVA技巧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.


Simply cast it:

HttpRequest request = (HttpRequest)WebRequest.Create(address);

This will throw an exception if the cast is not successful.

The as operator will return a null if the cast is not successful:

HttpRequest request = WebRequest.Create(address) as HttpRequest;
// if cast failed, request == null

So, this would be closer to a TryCast.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜