StevieB
StevieB

Reputation: 6533

What does {0} mean in String.Format?

E.g. in the following example:

string commandText = string.Format("Select * from {0}", filename);

How does the above work?

Upvotes: 2

Views: 24632

Answers (5)

gymbrall
gymbrall

Reputation: 2063

The {0} is a reference to the first argument passed after the format string.

In your case, "Select * from {0}" is the format string and filename is the first argument.

As an example:

String.Format("Select * from {0}{1}{0}","this","database")

would return:

"Select * from thisdatabasethis"

Upvotes: 1

JamieSee
JamieSee

Reputation: 13010

It is an indexer to the arguments presented after the “Select * from {0}” and can be combined with format specifiers as well. See the documentation for String.Format Method. However, you should NEVER EVER create a SQL command this way as it is vulnerable to SQL Injection attacks. You should always parameterize SQL queries. See the How To: Protect From SQL Injection in ASP.NET article on MSDN.

Upvotes: 1

Jeff
Jeff

Reputation: 14279

{0} refers to the second parameter passed into String.Format. {1} refers to the third, {2} to the fourth, etc. For example:

String.Format("The {0} brown {1} jumps {2} the {3} dog.", "quick", "fox", "over", "lazy")

Evaluates to

"The quick brown fox jumps over the lazy dog."

Upvotes: 6

Alexander Corwin
Alexander Corwin

Reputation: 1157

{0} is a placeholder for the first object given; in this case that's filename, so it will insert whatever filename evaluates to in place of {0}. Similarly, of course you could use {1} and that would be replaced with the second parameter passed, etc.

Upvotes: 12

user1108948
user1108948

Reputation:

It means the value of filename. Please see MSDN.

Upvotes: 2

Related Questions