Search code examples
c#lambdadelegatesactionanonymous-methods

c# Action<T> How to handle with anonymous methods


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?


Solution

  • 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.