How to convert TryCast in c#?

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.


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;

Tags:

C#

Asp.Net