operator(+) overloading in c#

  • Thread starter Thread starter enahar
  • Start date Start date
E

enahar

Dear Sir/Madam,

I have 2 lists as following:

ApproverListBE appList1;

ApproverListBE appList2 ;

I want to add the above 2 lists.How do I override the + operator.



Kind Regards,
 
It depends on how you implemented ApproverListBE.
For this example, I assume ApproverListBE derives from ArrayList:

public class ApproverListBE : System.Collections.ArrayList
{
public static ApproverListBE operator+(ApproverListBE list1,
ApproverListBE list2)
{
ApproverListBE combinedList = new ApproverListBE();
combinedList.AddRange(list1);
combinedList.AddRange(list2);
return combinedList;
}
}

You could then do something like:

ApproverListBE x = new ApproverListBE();
ApproverListBE y = new ApproverListBE();
x.Add(1);
x.Add(3);
y.Add(10);
y.Add(12);
y.Add(14);
ApproverListBE z = x + y;
// z now contains 1,3,10,12,14


Of course, you have to change the implementation of your + overload if
you didn't derive from ArrayList (because you probably won't have the
AddRange method). If you implement ICollection, you should be able to
implement the functionality using the CopyTo() method.
Hope that helps get you started.

Joshua Flanagan
http://flimflan.com/blog
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top