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.
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.
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}";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With