Casting VS Converting an Object Tostring, When Object Really Is a String

Casting vs Converting an object toString, when object really is a string

The two are intended for different
purposes. The ToString method of any
object is supposed to return a string
representation of that object. Casting
is quite different, and the 'as' key
word performs a conditional cast, as
has been said. The 'as' key word
basically says "get me a reference of
this type to that object if that
object is this type" while ToString
says "get me a string representation
of that object". The result may be the
same in some cases but the two should
never be considered interchangeable
because, as I said, they exist for
different purposes. If your intention
is to cast then you should always use
a cast, NOT ToString.

from http://www.codeguru.com/forum/showthread.php?t=443873

see also http://bytes.com/groups/net-c/225365-tostring-string-cast

Is it better to do toString() or cast the Object to String

ToString will work with all objects (as long as they are not null). If you cast to a String then the object has to be a String, otherwise it will fail. So my guess is that you want a toString() call, but it depends on what you want to do!

Casting to string versus calling ToString

  • (string)obj casts obj into a string. obj must already be a string for this to succeed.
  • obj.ToString() gets a string representation of obj by calling the ToString() method. Which is obj itself when obj is a string. This (should) never throw(s) an exception (unless obj happens to be null, obviously).

So in your specific case, both are equivalent.

Note that string is a reference type (as opposed to a value type). As such, it inherits from object and no boxing ever occurs.

Difference between .ToString and as string in C#

If Session["SessionTheme"] is not a string, as string will return null.

.ToString() will try to convert any other type to string by calling the object's ToString() method. For most built-in types this will return the object converted to a string, but for custom types without a specific .ToString() method, it will return the name of the type of the object.

object o1 = "somestring";
object o2 = 1;
object o3 = new object();
object o4 = null;

string s = o1 as string; // returns "somestring"
string s = o1.ToString(); // returns "somestring"
string s = o2 as string; // returns null
string s = o2.ToString(); // returns "1"
string s = o3 as string; // returns null
string s = o3.ToString(); // returns "System.Object"
string s = o4 as string; // returns null
string s = o4.ToString(); // throws NullReferenceException

Another important thing to keep in mind is that if the object is null, calling .ToString() will throw an exception, but as string will simply return null.

(String) or .toString()?

casting to a String is cheaper since that doesn't require an external function call, just internal type checking.

C# Options to explicitly cast an object as a string

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.

Is there a difference between the ToString method and casting to string?

There is a difference, yes. Every object has a ToString method, but not every object can be cast to a string.

int i = 10;
string s1 = i.ToString(); // OK
string s2 = (string)i; // Compile error.

object o = 10;
string s3 = o.ToString(); // OK
string s4 = (string)o; // Runtime error.

What is difference between .toString() and (String) cast in Java

When the runtime type of the instance returned by session.getAttribute("MyKeyValue") is not a String, casting it to String throws a ClassCastException.

On the other hand, session.getAttribute("MyKeyValue").toString() always works (assuming session.getAttribute("MyKeyValue") is not null), since all Objects have an implementation of the toString() method.

BTW, since session.getAttribute("MyKeyValue") doesn't return a String, it is likely that it returns a Boolean (since you expect Boolean.parseBoolean() to work), so if that is the case, instead of converting it to String and then to Boolean, you can just cast it to Boolean :

Boolean myBoolVal = (Boolean) session.getAttribute("MyKeyValue");

What's the difference between casting an int to a string and the ToString() method in C#

Well, ToString() is just a method call which returns a string. It's defined in object so it's always valid to call on anything (other than a null reference).

The cast operator can do one of four things:

  • A predefined conversion, e.g. int to byte
  • An execution time reference conversion which may fail, e.g. casting object to string, which checks for the target object being an appropriate type
  • A user-defined conversion (basically calling a static method with a special name) which is known at compile-time
  • An unboxing conversion which may fail, e.g. casting object to int

In this case, you're asking the compiler to emit code to convert from int to string. None of the above options apply, so you get a compile-time error.

What happens when calling Object.ToString when the actual type is String

1) From the open-source dotnet sources at https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/String.cs:

// Returns this string.
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this;
}

The override just returns this.

2) I would just use var bar = foo; instead of the cast or the .ToString(). If you only have an object, then yes .ToString() is preferred.



Related Topics



Leave a reply



Submit