Lets say we have the folowing code.
var foo = "I am a string";
Object obj = foo;
var bar = obj.ToString();
What is actually happening?
Witch one is better to do?
var bar = obj.ToString();
var bar = (string)obj;
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.
ToString is a method defined in the Object class, which is then inherited in every class in the entire framework.
The ToString method in the String class has been overwritten with an implementation that simply returns itself. So there is no overhead in calling ToString() on a String-object.
So, I don't think there's anything to worry about.
Also, I would go with the first option. It's more readable, and you should always get a result, no matter what type "obj" is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With