Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameters vs String interpolation

Tags:

c#

sql

What is the advantage of using parameters over using string interpolation?

Is this

SELECT * FROM dbo.Posts WHERE Author = @p0", userSuppliedAuthor;

any better than

$@SELECT * FROM dbo.Posts WHERE Author = {userSuppliedAuthor}";

?

like image 266
nPcomp Avatar asked Jan 31 '17 14:01

nPcomp


People also ask

What is string interpolation and how does it work?

When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. This feature is available starting with C# 6. String interpolation provides a more readable, convenient syntax to format strings. It's easier to read than string composite formatting.

Is there a compile time relationship between string arguments and string interpolation?

There’s no compile-time relationship between a format string and its arguments. String interpolation improves on that, so we’re taking advantage of it. We’re declaring the intent of our code as explicitly as possible so that future developers can easily understand what they’re about to modify.

What is an interpolated string in C?

C# language specification. See also. The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations ...

What happens when an interpolated string is resolved to a string?

When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. This feature is available starting with C# 6.


Video Answer


2 Answers

String interpolation is just a syntax sugar for formatting string. It gives you no protection against SQL injection. You should use SQL parameters to provide values for your query.

Consider - what if userSuppliedAuthor equals to

'Bob' OR 1 = 1

Or even

'Bob'; DROP TABLE Users;

Further reading SQL Injection

like image 81
Sergey Berezovskiy Avatar answered Oct 07 '22 09:10

Sergey Berezovskiy


In addition to SQL injection issues mentioned by Sergey, you can have issues with totally valid strings that contain certain characters, like "'", "." and "@" characters that mean things to SQL and need to be handled. It's always best to parameterize queries to prevent these issues, not only with injection when going straight from user input, but even something as simple as an email address or a possessive in a title.

like image 37
Andrew Avatar answered Oct 07 '22 09:10

Andrew