C# – Is it good practice to encapsulate many parameters that are alike into a struct

c++parametersstruct

Basically, I have something like the following:

public string SomeDBMethod(string server, string dbName, string userName, string password,...)

Is it good practice to refactor it to the following:

public string SomeDbMethod(DBParams parameters, ...)

Where DBParams is defined as follows:

public struct DBParams
{
  string Server {get;set;}
  string DbName {get;set;}
  string UserName {get;set;}
  string Password {get;set;}
}

My point is really to be able to pass around less parameters as I find functions with long parameter lists really quite ugly.

I have also found that there are some limitations to this approach: if SomeDbMethod is to be exposed as a web service method, I cannot use the DBParams struct as a parameter (as far as my understanding on the subject of web services go…which isn't very far).

So, is this too much trouble for little benefit or am I on to something here?

Best Solution

I always group parameters that go together into a single object - the code is cleaner this way, it is obvious that they are related to each other and always used together.

However, in most cases I use a class and not a struct. The benefits of structs were never clear to me, and they are pain in the back in many situations (I guess the webservices scenario is just one example).

You can make a class immutable if you don't want people to change it (if this was the reason to use struct)