How does the .ToString () method work?

Sometimes, when I call the class method .ToString() , it returns the full name of the class. But for some class / struct (e.g. Int32 ), it returns a string corresponding to the object (integer value). Does this mean that the Int32 class overrides the ToString() method, and the classes that return fully qualified names do not override it, but instead simply call the base ( Object s) ToString() method? Does the Object.ToString() implementation Object.ToString() full class name?

+6
source share
3 answers

Sometimes, when I call the ToString method, it returns the fully qualified name of the runtime type of the object that received the call.

Right.

But for some types, such as System.Int32 , ToString , the recipient value is converted to a string.

Right.

Does the structure of the System.Int32 method ToString ?

Yes.

To use other types, ToString methods return the full name of the type do not override ToString ?

This is probably true, yes. Of course, they can override the method and use the override method in the same way as the base class method, but that would be a little pointless.

So, in these cases, calling ToString just calls the implementation of System.Object ToString , which returns the full name?

Right.

You seem to have a clear understanding of how this works. My only correction would be that System.Int32 is a structure, not a class.

+17
source

Have you even tried to find the answer to your question?

http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

ToString is the primary formatting method in the .NET Framework. This converts the object to its string representation so that it is suitable for the display. (For information on formatting support in the .NET Framework, see Formatting Types.)

The implementation of the ToString method by default returns the fully qualified name of the object type, as the following example shows.

Because Object is the base class of all reference types in the .NET Framework, this behavior is inherited by reference types that do not override the ToString method. The following example illustrates this. It defines a class called Object1, which takes the default implementation of all members of the Object. Its ToString method returns an object with the fully qualified type name.

+8
source

A few points regarding the ToString () method in C #.

  • The ToString () method is defined in the base class System.Object and, therefore, is available for all types and parameters.

  • The standard implementation of ToString () provided by the base class system.object will give you the fully qualified type name, including the namespace.

  • If you do not need the default implementation, you can override the ToString () method. Yes The ToString () method is valid. And where do you redefine it? You redefine it in a class where you do not need its default implementation.

0
source

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


All Articles