Closure in C#

This entry is part 10 of 19 in the series Programming Languages

After the success of Closure in Java we like to show you a good example in C# too.

C# has a very strong support for Lambda functions, because it needs to support the LINQ language constructs.

So defining a closure is quite easy. Best, it is possible to define a “delegate” , which is a typed function: the compiler will help you to avoid errors because will match the lambda function against the delegate.

The client code will look like
[csharp]FillInInputParamerers p = cmd => {
cmd.Parameters.Add("@utenteDaProfilare", SqlDbType.VarChar);
cmd.Parameters["@utenteDaProfilare"].Value = username;
return cmd;
DataSet result = execStoredProcedure("sp_GetProfiliUtente", p, "Utenti");[/csharp]
The trick will use the CSharp delegate keyword:

#region Delegatori
/// <summary>
/// The Lambda function </summary>
public delegate SqlCommand FillInInputParamerers(SqlCommand input);

/// <summary>
/// Metodo per delegare la gestione degli errori e l’esecuzione della stored procedure
/// </summary>
/// <param name="storedProcedureName"></param>
/// <param name="function"></param>
/// <param name="srcTable"></param>
/// <returns></returns>
public DataSet execStoredProcedure(string storedProcedureName, FillInInputParamerers function, string srcTable)
DataSet result = new DataSet();

string sp = storedProcedureName;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sp, conn);
cmd.CommandType = CommandType.StoredProcedure;
// Delegate the parameters
cmd = function(cmd);

SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result, srcTable);
catch (SqlException sqlEx)
result = null;
runtimeResult.KO(sqlEx.ErrorCode, sqlEx.Message, sqlEx.ToString());
catch (Exception ex)
result = null;
runtimeResult.KO(0, ex.Message, ex.ToString());
if (conn != null)
return result;


For more information take a look to the MS documentation

Series NavigationCappuccino: Objective-J

Leave a Reply