Jon.A
Jon.A

Reputation: 19

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") ...

Upvotes: 0

Views: 1971

Answers (4)

Matt
Matt

Reputation: 27016

In addition to the answer, there is another option to convert it to a string:

string session_test = (Session?["test"] ?? "").ToString();
if (session_test  == "abc") 
{ 
   // do anything
}

Note: For better readibility, I have declared a variable - but of course you can also use the expression inline in the ifstatement.

session_test will contain an empty string "" if:

  1. Session variable is null
  2. Session["test"] contains null or an empty string

In these cases no exception is thrown. So this way, you need no extra checking and can focus on the value itself - which makes the code easy to handle. However, if you do want to detect if "test" exists in Session, you will need an extra check (but that wasn't asked in the question).


Details:

The ?? Operator deals with null values - it replaces null by "", otherwise continues with the value if it is not null, allowing it to safely convert it into a string.

Since not only the value stored as "test", but also Session itself could be null, the ?[ operator is used:

Session?["test"] is passing null if Session is null, otherwise it passes the value stored for "test" in Session.

More information:

Upvotes: -1

Marc Wittmann
Marc Wittmann

Reputation: 2671

If you want to ignore null values: Throwing in the yoda condition:

"abc".Equals(Session["test"]);

You can always use the .Equals() Methods for comparing. It is wisely to use for complex types anyway but not necessarily for strings. You can use the Equals Method which never will throw an exception becuse "abc" is never null.

  • If Session["test"] is null, this will return false instead of throwing an exception, making it safer than .ToString().

  • If Session["test"] is a non-string type (like int), it will return false unless it overrides Equals in a compatible way.

This would also work for other data Types. It is sometimes less easy to read but I prefer using it in some cases.

Upvotes: 0

PMF
PMF

Reputation: 17288

As already pointed out in the comments above, there's a fourth possibility, which works with recent compiler versions:

if (Session["test"] is string test && test == "abc")
{
    // will get here only if the field was not null and is "abc"
}

The is operator returns false if the object is null, but if it is not null and the type matches, the value is assigned to the variable.

Upvotes: 0

Nikhil Mehta
Nikhil Mehta

Reputation: 365

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.

Upvotes: 1

Related Questions