Search code examples
c#castingexplicit

Options to explicitly cast an object as a string


I am a relative newbie to C# as most of my web development work has been in VB. In VB something like a DataRow Object or Session Object will implicitly cast to say a string. I can say:

If myDataRow("name") = "Fred" Then  ...

I appreciate that in C# this casting must be explicit, so my question - all three of the lines below compile and work as expected. The ToString() will throw an exception if the session object is null so I guess that option is less 'good' as I would have to check for null first, but is one option more efficient or considered better C# coding practice than the others? Thanks a lot.

if ((string)Session["test"] == "abc") ...
if (Session["test"] as string == "abc") ...
if (Session["test"].ToString() == "abc") ...

Solution

  • There are many good responses to this here: Direct casting vs 'as' operator?

    In short, the first option i.e. (string)Session["test"] == "abc" will throw a InvalidCastException if Session["test"] is not a string. Use this if you might want to throw an error on invalid cast.

    The second option Session["test"] as string == "abc" will return null if the object which is typecasted is not a string. This option requires an explicit null check to be done post conversion before actually using the result.

    If you definitely know that the object which you are typecasting is a string, you can use the first one and if in case it fails, you will definitely know that the cast failed and is easier to debug. If you are not sure of whether the object is a string, you might want to go for the second option.