I am passing 20+ arguments of different types to method. There should be some clean way to pass this. Can you please help me.
I can pass array of object having all these 20+ arguments but in target method I have to put checks on type. Is this good way to pass long list of arguments.
Code: Sample from code not full
private DataTable CreateDataTable(string[] args)
{
DataTable dt = new DataTable();
dt.Clear();
foreach (var arg in args)
{
dt.Columns.Add(arg);
}
return dt;
}
I can pass array in this method because all arguments are of same type.
DataTable dt = CreateDataTable(new string[] { "ProjectId",
"ParentProjectId",
"ProjectName",
"CreationDate");
Now here I have more than 20+ values of diff types like following
int projectId = 100;
int? parentProjectId = SomeCondition ? 10 : null;
string projectName = "Good Project"
DateTime createdDate = DateTime.Now;
.
.
.
In this method I would assign values to columns.
AssignValuesToDataTable(dt, Arguments list ......)
// Implementation would be like this. Here I am passing 20+ arguments.
private DataTable AssignValuesToDataTable(DataTable dt, arguments list ........)
{
DataRow row = dt.NewRow();
row["ProjectId"] = projectId;
.
.
.
dt.Rows.Add(row);
}
Can you please help. I am using C#4
EDIT:
Above code is an example from my real code but I am more interesting to know that what is best method to achieve this.
From Coding Horror (Jeff Atwood)
The more parameters a method has, the more complex it is. Limit the
number of parameters you need in a given method, or use an object to
combine the parameters.
Above quote is from this blog post.
Code Smells
Thanks.
Pass an object that represents the data instead:
with
of course, then the question becomes : why use
DataTableat all? since aProjectclass is a much better metaphor / mechanism for expressing that data, andList<Project>(orBindingList<Project>) is ideal for a collection of such.(hint: I very, very, very rarely use
DataTable– or maybe less frequently than that)