1

What is the difference between those two syntaxes?

Is there any situation where one must use String.Format rather than composite string?

Console.WriteLine("{0:d} {0:t}",DateTime.Now);
Console.WriteLine(String.Format("{0:d} {0:t}",DateTime.Now));
  • 2
    You don't have to use `string.Format` at all. Just use interpolated string `$"{DateTime.Now}"`. `Console.WriteLine` uses `String.Format` under the hood, so these two lines are the same. – FCin Sep 15 '18 at 13:39
  • Possible duplicate of [When is it better to use String.Format vs string concatenation?](https://stackoverflow.com/questions/296978/when-is-it-better-to-use-string-format-vs-string-concatenation) – Heretic Monkey Sep 15 '18 at 13:45

2 Answers2

3

There isn't any difference between them because

Console.WriteLine("{0:d} {0:t}",DateTime.Now);

that will call String.Format function by this overload function.

public virtual void WriteLine(String format, Object arg0)
{
    WriteLine(String.Format(FormatProvider, format, arg0));
}

console.WriteLine Source code

D-Shih
  • 44,943
  • 6
  • 31
  • 51
  • 3
    More specifically, it calls [`TextWriter.Write`](https://referencesource.microsoft.com/#mscorlib/system/io/textwriter.cs,352) which then calls `String.Format` – Heretic Monkey Sep 15 '18 at 13:44
0

I just noticed a situation where String.Format or interpolated string has to be used rather than normal composite string.

SqlConnection myConnection = new SqlConnection("......");
SqlDataAdapter myDataAdapter1 = new SqlDataAdapter("SELECT userAddress FROM tblUserData WHERE userName = '" + userName + "'", myConnection);
SqlDataAdapter myDataAdapter2 = new SqlDataAdapter("SELECT userAddress FROM tblUserData WHERE userName = '{0}'", userName, myConnection);
SqlDataAdapter myDataAdapter3 = new SqlDataAdapter(String.Format("SELECT userAddress FROM tblUserData WHERE userName = '{0}'", userName), myConnection);
SqlDataAdapter myDataAdapter4 = new SqlDataAdapter($"SELECT userAddress FROM tblUserData WHERE userName = '{userName}'",myConnection);

myDataAdapter2 is not working because of the incorrect parameters.

(Yeah, normally, SELECT statement is assigned to a string variable.)