Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Does String.Format call ToString of the input?

Tags:

string

c#

format

Does String.Format run ToString?

For example, if I have an object of a "complex" class, can I do:

 <i>String.Format("String rep. {0}",complexObj);</i>
like image 839
Yakov Avatar asked Apr 08 '14 14:04

Yakov


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

Why is C named so?

Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.


1 Answers

From the documentation:

How arguments are formatted:

Format items are processed sequentially from the beginning of the string. Each format item has an index that corresponds to an object in the method's argument list. The Format method retrieves the argument and derives its string representation as follows:

  • If the argument is null, the method inserts String.Empty into the result string.
  • If you call the Format(IFormatProvider, String, Object[]) overload and the provider parameter implements the ICustomFormatter interface, the argument is passed to the provider object's ICustomFormatter.Format(String, Object, IFormatProvider) method. If the format item includes a formatString argument, it is passed as the first argument to the method. If the ICustomFormatter implementation is able to provide formatting services, it returns the string representation of the argument; otherwise, it returns null and the next step executes.
  • If the argument implements the IFormattable interface, its IFormattable.ToString implementation is called.
  • The argument's parameterless ToString method, which is either overridden or inherited from the Object class, is called.

So yes, finally - as a fallback - the ToString method is called.

like image 125
Tim Schmelter Avatar answered Oct 04 '22 01:10

Tim Schmelter