Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to use string.Format() with just a string parameter?

Tags:

c#

.net

sql

I'm currently updating some old code at work. I ran into a number of lines where string.Format() is used for seemingly no reason. I'm wondering if there is some use for using string.Format() without additional parameters, but I can't think of any.

What's the difference between this:

string query = String.Format(@"select type_cd, type_shpmt from codes");

and this:

string query = "select type_cd, type_shpmt from codes";

I also don't think that the @ is needed since it doesn't need to be a string literal, and it's not a multi-line string.

like image 701
red circle Avatar asked May 31 '19 13:05

red circle


2 Answers

Cut and paste failures. Someone didn't take the time to cleanup the code. There is no reason to use string.Format. Simply delete it and assign directly.


⚠️ Warning ⚠️

If the person is using the Format to combine parameters be wary; one should use the SQLCommand and SQLParameter class to avoid sql injection.

like image 110
ΩmegaMan Avatar answered Oct 27 '22 19:10

ΩmegaMan


While Format should be deleted, spare @ and make query being more readable:

  string query = 
     @"select type_cd, 
              type_shpmt 
         from codes";

If you want to modify table, field names etc. (which you can't do via Sql Parameters) try using string interpolation:

  string myTableName = "codes";

  ...

  string query = 
     $@"select type_cd, 
               type_shpmt 
          from {myTableName}";
like image 38
Dmitry Bychenko Avatar answered Oct 27 '22 21:10

Dmitry Bychenko