Reputation: 23
I've recently explored c# to myself. But stuck with this problem.
So I have a method dbExec
public void dbExec(Action<OleDbCommand> func)
{
using (var conn = new OleDbConnection(connStr))
{
conn.Open();
var cmd = conn.CreateCommand();
func(cmd);
}
}
delegate,
public delegate void DelCmd(OleDbCommand cmd);
and another method:
public ICollection<string> CheckUserPermissions()
{
List<string> logins = new List<string>();
DelCmd delCmd = delegate(OleDbCommand cmd)
{
cmd.CommandText = "SELECT PERMISSIONS.LOGIN FROM PERMISSIONS";
using (var rdr = cmd.ExecuteReader()) while (rdr.Read()) logins.Add(rdr["LOGIN"].ToString());
};
dbExec(delcmd);
return logins;
}
The problem with dbExec(delcmd);
statement. The error is "delcmd doesn't exist in current context". How to pass an anonymous method as a parameter to another method with Action declared parameter?
Upvotes: 2
Views: 16025
Reputation: 1891
You could also avoid defining a delegate altogether.
Like this:
public ICollection<string> CheckUserPermissions()
{
List<string> logins = new List<string>();
Action<OleDbCommand> delCmd = cmd =>
{
cmd.CommandText = "SELECT PERMISSIONS.LOGIN FROM PERMISSIONS";
using (var rdr = cmd.ExecuteReader())
while (rdr.Read()) logins.Add(rdr["LOGIN"].ToString());
};
dbExec(delCmd);
return logins;
}
Edit: I actually mean what Servy wrote in the comment on the other answer, but he described it way better.
Upvotes: 6
Reputation: 236188
You have a typo - it should be delCmd
instead of delcmd
. C# is a case-sensitive language
UPDATE: DelCmd
is not same as Action<OleDbCommand>
- that is different types, and you even can't cast delegates to each other. But you can create new action delegate:
dbExec(new Action<OleDbCommand>(delCmd));
Upvotes: 1