In C# 3.5, How do you pass which method to call on an object as a parameter
.net-3.5, c#, delegates, refactoring
Solution
Sure. Just define a delegate like so:
public delegate bool GetUsername(string clientID, out string username);
And then pass it into your function and call it:
private static bool TryGetLogonUserId(IGetClientUsername clientController, string sClientId, out int? logonUserId, GetUsername func)
{
string username;
if (func.Invoke(sClientId, out username))
{
// ... snip common code ...
}
return false;
}
To call the function with the delegate, you'll do this:
TryGetLogonUserId(/* first params... */, clientController.GetClientUsername);
Problem
I have two methods in C# 3.5 that are identical bar one function call, in the snippet below, see clientController.GetClientUsername vs clientController.GetClientGraphicalUsername ``` private static bool TryGetLogonUserIdByUsername(IGetClientUsername clientController, string sClientId, out int? logonUserId) { string username; if (clientController.GetClientUsername(sClientId, out username)) { // ... snip common code ... } return false; } private static bool TryGetLogonUserIdByGraphicalUsername(IGetClientUsername clientController, string sClientId, out int? logonUserId) { string username; if (clientController.GetClientGraphicalUsername(sClientId, out username)) { // ... snip common code ... } return false; } ``` Is there a way (delegates, lamda's ?) that I can pass in which method on clientController I want to call? Thanks!