Reputation: 12560
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);
}
Upvotes: 2
Views: 287
Reputation: 21881
ICollection temp;
if (includeAllCheck.Checked)
{
temp = currentMessages;
}
else
{
temp = currentLeads;
}
if (SelectedLead == (temp.Count - 1))
SelectedLead = 0;
else
SelectedLead += 1;
Upvotes: 1
Reputation: 131746
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.
Upvotes: 8