Reputation: 2336
Is there a elegant way to pass multiple arguments to a constructor?
This is my constructor:
public _Empresa(string n, string r, string d, int l, string c, string f, string t, string m, string o)
{
e_nombre = n;
e_rfc = r;
e_direccion = d;
e_delegacion = l;
e_cp = c;
e_referencias = f;
e_telefono = t;
e_email = m;
e_observaciones = o;
}
Lately in a windows form I call that constructor
public _Empresa empresa
{
get
{
return new _Empresa(_nombre.Text, _rfc.Text, _direccion.Text, int.Parse(_delegacion.SelectedValue.ToString()), _cp.Text, _referencias.Text, _telefono.Text, _email.Text, _observaciones.Text);
}
}
They aren't same type so no chance of sending an array. What other options do i have?
Upvotes: 1
Views: 131
Reputation: 25844
If some of those properties are related, you could group them into smaller classes on their own (so you could pass in an instance of that class to the constructor of your class). However that would just spread your initialization to two or three smaller objects, so you should do it only if it makes logical sense for your code, not only to make your constructor more readable.
One thing that may make your code more readable is using named parameters and some indentation:
new _Empresa(
n: _nombre.Text,
r: _rfc.Text
...
);
which would also look better if the parameter names were more self-descriptive
Upvotes: 2
Reputation: 60468
You can pass in a class that has properties you need in your constructor.
the arguments class
public class EmpresaConstructorArguments
{
public string Nombre { get;set }
// ...
}
the constructor
public _Empresa(EmpresaConstructorArguments arg)
{
e_nombre = arg.Nombre;
// ...
}
or
private EmpresaConstructorArguments Arguments;
public _Empresa(EmpresaConstructorArguments arg)
{
this.Arguments = arg;
}
Check out MSDN - ProcessStartInfo Class.
Specifies a set of values that are used when you start a process.
Another approach is to pass in the values with named arguments.
Assuming your class looks like this
public _Empresa empresa
{
public string Nombre { get; set }
// ...
}
you can do
new _Empresa { Nombre : _nombre.Text }
Upvotes: 4
Reputation: 7105
You could create an object that contains all of the arguments and pass that instead. The fact there's so many of them tells you they probably have some kind of relation that may be worthy of a class anyway.
Upvotes: 1