3

Passing List & lt; Domain Object & gt; to a Waiting method list < obj...

 2 years ago
source link: https://www.codesd.com/item/passing-list-domain-object-to-a-waiting-method-list-object.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Passing List & lt; Domain Object & gt; to a Waiting method list < object & gt;

advertisements

I know I'm missing something fundamental with either generics or covariance, and I was hoping there is a better way to do what I am doing.

I have a method that takes a list of domain objects and turns it into an HTML table:

public String GenerateTable(List<object> Data, String[] Properties,
    String[] ColumnHeaders = null)
{
}

When I call the method, I find myself having to do this:

List<Customer> cust = GetCustomers();
List<object> oCust = new List<object>;
foreach (Customer c in cust)
    oCust.Add((object)c);

string table = GenerateTable(oCust, new string[] { "CustNbr", "CustName" });

I believe with covariance I can simply:

List<object> oCust = cust;

But I'm looking for a better solution all-around -- eliminate the necessity to create a completely new list each time I run this method. It's not a performance or memory issue, as these lists are always relatively small, but I'd like to understand what is the best (or at least better) way to accomplish this.


You should change GenerateTable to accept an IEnumerable of objects instead of a list. Then you won't have to convert your Customer list to a list of objects.

public String GenerateTable(IEnumerable<object> Data, String[] Properties, String[] ColumnHeaders = null)

The problem with your original version is that GenerateTable could attempt to add a non-Customer object to the List. IEnumerable works because it is read only. You can read more about it here, if you are interested.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK