Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

Lets say we have the folowing code.

var foo = "I am a string";
Object obj = foo;
var bar = obj.ToString();

What is actually happening?

  1. Cast the obj to a string and then calls the ToString Method?
  2. Calls the ToString method on obj which is the override of string without casting?
  3. Something else?

Witch one is better to do?

  1. var bar = obj.ToString();
  2. var bar = (string)obj;
like image 349
Panagiotis Lefas Avatar asked Jun 23 '15 08:06

Panagiotis Lefas


2 Answers

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.

like image 183
bright Avatar answered Oct 21 '22 23:10

bright


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.

like image 21
Steven Lemmens Avatar answered Oct 21 '22 21:10

Steven Lemmens