Comments (8)
Ya know I was tempted to add a comment to the feature request for params IEnumerable<T>
to also ask for something like params IDictionary<string, T>
where the latter would be satisfied by using named arguments:
void Execute(string command, params IDictionary<string, object> arguments) {
// do stuff here
}
Execute("SELECT * FROM table WHERE name = @name AND date = @date;",
name: "Joe",
date: DateTime.Today
);
// equivalent to
Execute("SELECT * FROM table WHERE name = @name AND date = @date;",
new Dictionary<string, object>() {
{ "name", "Joe" },
{ "date", DateTime.Today }
}
);
What do you think?
from roslyn.
That's pretty great. Very similar to python's **kwargs
and would solve most of my needs and be a nice boon to APIs that need this type of functionality. However, like the previous discussion if the usage is primarily for iterating and with a small number of arguments it might be worthwhile to create something more specialized. Dictionaries are pretty lightweight but certainly an object with an array of KeyValuePairs would be cheaper.
from roslyn.
Absolutely. The compiler could emit a specialized struct which implements the interface (as large and as obnoxious as that is).
For your use case (an SQL statement) I imagine that we'll see more of a push towards string interpolation via FormattedString
, although that lacks the capacity to get the names of the holes at the moment which is a limiting factor.
from roslyn.
If I wore my DBA hat, I'd groan at the idea of replacing an rpc to sp_executeSql
to a FormattedString
that is potentially susceptible to sql injection. I think formattedString is really cool and will help in general, but I see this still as a useful construct for sql.
from roslyn.
If the API accepted FormattedString
it could apply its own interpolation strategy so that the string contained generated parameter names rather than embed the values, something akin to:
public static int Execute(this SqlConnection connection, FormattedString command) {
using (SqlCommand command = connection.CreateCommand()) {
int length = command.Args.Length;
string[] parameterNames = new string[length];
for (int i = 0; i < length; i++) {
string parameterName = "@p" + i;
parameterNames[i] = parameterName;
command.Parameters.AddWithValue(parameterName, command.Args[i]);
}
command.CommandText = String.Format(command.FormatString, parameterName);
return command.ExecuteNonQuery();
}
}
Which you should be able to call like this:
string name = "Joe";
DateTime date = DateTime.Today;
int result = connection.Execute($"SELECT * FROM dbo.table WHERE user = {user} AND name = {name};");
Which would execute the following SQL:
SELECT * FROM dbo.table WHERE user = @p0 AND name = @p1;
-- @p0 NVARCHAR(4000) N'Joe'
-- @p1 DATETIME2 '2015-01-21 ...'
Of course if FormattedString
also carried the hole names then you could name the parameters better.
from roslyn.
I retract my comment FormattedString actually does look really good for that goal. There are other cases where I won't be passing a string parameter and it would be useful to be able to use keyword arguments.
from roslyn.
We have no expectation of ever doing anything like this.
from roslyn.
What I ended up doing is create a dummy class like this:
public class Params : Dictionary<string, object> { } //syntax sugar
And then use it like this with Dapper to prevent (slow) reflection:
connection.ExecuteReader("SELECT * FROM Table WHERE ID=@ID", new Params { ["ID"] = 123 };
from roslyn.
Related Issues (20)
- Automatic exception xml tag when using static class such as ArgumentNullException HOT 2
- Allow the Visual Studio "Sync Namespaces" tool to work at the folder level, not just Project and Solution.
- Refactoring suggestion -> Move to new file needs a confirmation dialog
- Reenable BC30645ERR_InvalidOptionalParameterUsage1b
- [Automated] PRs inserted in VS build feature.debugger.main-35215.202
- Inconsistent report of CS8156 when using generically constrained interfaces and [UnscopedRef]
- Sourcelink does not debug merged partial classes
- Advanced analysis options are unreliable, confusing and poorly documented
- EditorConfig "modern" vs legacy priority revert related documentation updates
- CS8344 error even with C# 13 (ref in iterators/async) HOT 1
- Editor and debugger don't agree on breakpoint range
- CS8602 should look deeper ("Dereference possibly null reference") HOT 3
- Microsoft.VisualStudio.LanguageServices.DevKit.csproj attempted to copy files to output directory during design time build HOT 1
- Reference highlighting doesn't work for some types from constructor expression
- Reference highlighting doesn't work from primary constructor base call constructor call
- `InvalidOperationException` in `SemanticTokensHelpers` when applying embedded classification on verbatim string
- Should collapse separate comment blocks separately
- Anonymous-Params-delegate is generated incorrectly with AllowRefStructFlag HOT 3
- Flaky test: Microsoft.CodeAnalysis.MSBuild.UnitTests.NewlyCreatedProjectsFromDotNetNew.ValidateVisualBasicTemplateProjects HOT 1
- Diagnostics from C# interactive window won't go away
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from roslyn.