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!
While you can pass a delegate as a parameter, I suggest going with a different route. Encapsulate the body of the if
statement which involves common code in another function and call that one in both functions.
Visual Studio has a "Refactor ->
Extract Method" feature in the context menu. You can just fill in one of the bodies, select the body and use that feature to extract a method out of it automatically.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With