How does the .ToString() method work?

你。 提交于 2019-11-28 01:12:46

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

Correct.

But for some types, such as System.Int32, ToString returns the value of the receiver converted to a string.

Correct.

Does the System.Int32 struct override the ToString method?

Yes.

Do other types whose ToString methods return the fully-qualified type name not override ToString?

That is probably the case, yes. Of course, they could override the method and have the overriding method do exactly the same thing as the base class method, but that would be a bit pointless.

So in those cases, calling ToString just calls the System.Object implementation of ToString, which returns fully qualified name?

Correct.

You seem to have a solid grasp of how this works. My only correction would be to note that System.Int32 is a struct, not a class.

Have you even tried to search for answer to your question?

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

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

The default implementation of the ToString method returns the fully qualified name of the type of the Object, 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 named Object1 that accepts the default implementation of all Object members. Its ToString method returns the object's fully qualified type name.

Few points regarding the ToString() method in C#.

  1. ToString() method is defined in the base System.Object class and hence its available for all the types and parameters to use.

  2. The default implementation of ToString() that is provided by the system.object base class will give you the complete name of the type including the namespace.

  3. If you don't want the default implementation, then you can override the ToString() method. Yes ToString() method is overridable. And where do you override it? You override it in the class where you don't want its default implementation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!