tags:

views:

85

answers:

2

Hello SO:

I have a subroutine that changes its operation slightly to include either one list or the other then perform the same operation. Since it is just counting the number of items in the list, I figure there is probably an easy way to get the item count regardless of the list type.

Thanks in advance!

EDIT:

private List<Message> currentMessages;
private List<Lead> currentLeads; 
...
private void nextLeadBtn_Click(object sender, EventArgs e)
    {
        object temp;
        if (includeAllCheck.Checked)
        {

            temp = currentMessages;
            if (SelectedLead == (currentMessages.Count - 1))
                SelectedLead = 0;
            else
                SelectedLead += 1;
        }
        else
        {
            temp = currentLeads;
            if (SelectedLead == (currentLeads.Count - 1))
                SelectedLead = 0;
            else
                SelectedLead += 1;  
        }
        // This is what I want to replace the above with
        //if (SelectedLead == ((List)temp).Count - 1) //obviously this does not work
        //    SelectedLead = 0;
        //else
        //    SelectedLead += 1;




        LoadPreviews(includeAllCheck.Checked);
    }
+8  A: 

You can always use ICollection.Count, if you don't want to deal with generics. List<T> implements ICollection, so you can always access that.

EDIT: So now that you've posted your code, you can just change the line:

if (SelectedLead == ((List)temp).Count - 1)  // won't compile, of course

to

if (SelectedLead == ((ICollection)temp).Count - 1)  // happy as a clam

In fact, an even better option would be to change the declaration of object temp to ICollection temp to better convey the type information, and avoid all of this casting nonsense altogether.

LBushkin
Perfect, this did exactly what I needed. Thanks!
Anders
Also took your better option. Thank you again.
Anders
+1  A: 
ICollection temp;
        if (includeAllCheck.Checked)
        {

            temp = currentMessages;            
        }
        else
        {
            temp = currentLeads;

        }
if (SelectedLead == (temp.Count - 1))
                SelectedLead = 0;
            else
                SelectedLead += 1;
Ben Robinson
This was the proper solution to my inquiry. LBushkin gave it away just before you did. Thanks for your input, however!
Anders