Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Array Method help

Tags:

methods

c#

Could some one please show me how I can rewrite the below method in a better and more elegant way?

// in class------------------

    public static void RefreshAllDropdownlists(DropDownList ddlRemoveUsersFromRole, DropDownList ddlAddUsersToRole, DropDownList ddlAddAllUsersToRole, DropDownList ddlRemoveAllUsersFromRole, DropDownList ddlDeleteAllUsersFromRole)
    {
        ddlRemoveUsersFromRole.ClearSelection();
        ddlAddUsersToRole.ClearSelection();
        ddlAddAllUsersToRole.ClearSelection();
        ddlRemoveAllUsersFromRole.ClearSelection();
        ddlDeleteAllUsersFromRole.ClearSelection();
    }

// in codebehind------------------

UserGvUtil.RefreshAllDropdownlists(ddlRemoveUsersFromRole, ddlAddUsersToRole, ddlAddAllUsersToRole, ddlRemoveAllUsersFromRole, ddlDeleteAllUsersFromRole);

Thank you!

like image 203
John Walsh Avatar asked Dec 23 '22 01:12

John Walsh


2 Answers

Use the params parameter modifier to pass an array of DropDownLists :

public static void RefreshAllDropdownlists(params DropDownList[] dropDownLists)
{
    foreach (DropDownList ddl in dropDownLists)
    {
        ddl.ClearSelection();
    }
}

Usage is is the same as with your current method

like image 172
Thomas Levesque Avatar answered Jan 08 '23 09:01

Thomas Levesque


var listsToRefresh = new List<DropDownList>
                {
                    ddlRemoveUsersFromRole,
                    ddlAddUsersToRole,
                    ddlAddAllUsersToRole,
                    ddlRemoveAllUsersFromRole,
                    ddlDeleteAllUsersFromRole
                };
listsToRefresh.ForEach(l=>l.ClearSelection());

There are many ways to do this, I would prefer this one. If all you are doing is performing ClearSelection() on each one, then there is no need to create a method for that one line of code. However, if you want to do some more work on each DropDownlist, then I think the use of an extension method would keep it elegant.

 public static class DropDownListExtensions
    {
        public static void Reset(this DropDownList dropDownList)
        {
            dropDownList.ClearSelection();
            //... do more stuff

        }
    }

listsToRefresh.ForEach(l=>l.Reset());
like image 25
Tion Avatar answered Jan 08 '23 09:01

Tion