6

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;
DavidG
  • 113,891
  • 12
  • 217
  • 223
Panagiotis Lefas
  • 1,113
  • 2
  • 12
  • 24

3 Answers3

3

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.

Steven Lemmens
  • 620
  • 5
  • 18
2

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.

bright
  • 4,700
  • 1
  • 34
  • 59
0

What is actually happening?

Your code can actually be something like this

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

C# string keyword is an alias to String class. The ToString method that you called simply uses polymorphism mechanism to call proper ToString implementation. As you may know string is a reference type and a child class of Object

Witch one is better to do?

From this answer.

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.

Community
  • 1
  • 1
farid bekran
  • 2,684
  • 2
  • 16
  • 29