Home > Uncategorized > As String, ToString and (string)

As String, ToString and (string)

Three ways to cast an object to a string .ToString(), as String, and (string), what’s the difference?

((object)1).ToString()  equals "1"
((object)1) as string  equals null
(string)((object)1) throws an exception

Basically, "ToString()" calls a method on "object" or in the closest derived class that overrides the ToString() method.

"As string" performs a cast, but returns null rather than an exception is the cast is not implicitly possible.

(string) peroforms the same cast, but throws an exception on failure.

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: