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));
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));
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
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.)