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

Let's say we have the following code.

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

What is really going on?

  • Passing obj to a string and then calling the ToString method?
  • Calls the ToString method for obj, which is an override of a string without casting?
  • Something else?

Witch is better to do?

  • var bar = obj.ToString();
  • var bar = (string)obj;
+6
source share
3 answers

1) From open source point-mail 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; } 

Completion returns only this .

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

+2
source

ToString is a method defined in the Object class, which is then inherited in each class in the entire structure.

The ToString method in the String class has been overwritten by an implementation that simply returns itself. Thus, there is no overhead when calling ToString () on a String object.

So, I don’t think to worry about anything.

In addition, I would go with the first option. This is more readable, and you should always get the result, regardless of the type of "obj".

+2
source

What is really going on?

Your code can really be something like this

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

With # string keyword is an alias of the string class. The ToString method you called just uses the polymorphism mechanism to call the correct ToString implementation. As you know, string is a reference type and a child class of Object

Witch is better to do?

From this answer.

Both are for different purposes. The ToString method for any object should return a string representation of this object. Casting is completely different, and the keyword “how” does conditional cast, as already mentioned. The keyword “how” basically says “make me reference this type to this object if this object is type”, while ToString says: “Get me a string representation of this object”. The result may be the same in some cases, but two should never be considered interchangeable, because, as I said, they exist for different purposes. If you intend to quit then you should always use cast, NOT ToString.

0
source

Source: https://habr.com/ru/post/989588/


All Articles