Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# 3.5, How do you pass which method to call on an object as a parameter

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!

like image 445
David Laing Avatar asked Jun 22 '09 11:06

David Laing


2 Answers

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.

like image 164
mmx Avatar answered Oct 05 '22 04:10

mmx


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);
like image 33
Josh G Avatar answered Oct 05 '22 05:10

Josh G