Search code examples
c#parameterscoding-style

Method that takes a lot of parameters


I have a quite general question about parameters in C#.

I sometimes end up with methods that need a lot of parameters, specifically when making GridViews searchable.

Take this example:

searchSQL(
    tbEID.Text, 
    tbSID.Text, 
    tbCID.Text, 
    tbSP.Text, 
    tbSA.Text, 
    tbSMF.Text, 
    tbSS.Text, 
    tbSSC.Text, 
    tbSST.Text, 
    tbSIPA.Text, 
    (string)ViewState["SortExpression"], 
    (string)ViewState["SortDirection"], 
    (tbFromDate.Text == "") ? (DateTime?)null : Convert.ToDateTime(tbFromDate.Text), 
    (tbToDate.Text == "") ? (DateTime?)null : Convert.ToDateTime(tbToDate.Text), 
    (tbSAC.Text == "") ? (int?)null : Convert.ToInt32(tbSAC.Text)
);

It works and everything, but it just doesn't look very good IMO.

What would be some possible ways to make this look better? The only way I can think of is to shrink it down by using lists, something like:

searchSQL(List<string>, List<DateTime>, int)

any other, better alternatives?


Solution

  • Use a class to represent the real world data that is being modelled.

    class YourNameHere
    {
        public string EID { get; set; }
        ...
    }
    

    That way if you needed to add a value, you can just modify the class - the other code wouldn't have to change, you wouldn't have to be dependent on the index of the properties matching, etc.

    You might want to read up on the concept of encapsulation.