Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// This is all pseudo code, never tested, just to give a quick idea of a delegate
// Just like you use the "class" keyword to define the characteristic of an object, you can use
// "delegate" to define the characteristic of a method.
public delegate void PerformDatabaseAction(SqlConnection sqlConn);
public static class DatabaseHelpers
{
public static void DoDatabaseAction(PerformDatabaseAction theDbAction)
{
var sqlConnection = new SqlConnection("somesqlconnectionstring");
theDbAction(sqlConnection);
sqlConnection.Dispose();
}
}
public class ChargePointDataRetriever
{
private List<ChargePoint> _data;
private void GetData(SqlConnection conn)
{
var result = conn.ExecuteQuery("SELECT * FROM ChargePoint");
_data = result.ToArray();
}
public void Start()
{
// The parameter of the function is the PerformDatabaseAction delegate. Because the GetData method above matches the signature of
// the delegate (void as return and SqlConnection as param), we can just pass the method as parameter.
PerformDatabaseAction theDbAction = GetData;
DatabaseHelpers.DoDatabaseAction(theDbAction);
Console.PrintLine(_data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment