user1993843
user1993843

Reputation: 155

c# operator overloading usage

public static ListOfPeople operator +( ListOfPeople x, Person y)
    {
        ListOfPeople temp = new ListOfPeople(x);
        if(!temp.PeopleList.Contains(y))
        {
            temp.PeopleList.Add(y);
        }
        temp.SaveNeeded = true;
        return temp;
    }

So, I've never used the overload functionality of operators, and I'm trying to make sense of how to add objects from my class (Person) to my Collection class (ListOfPeople).

ListOfPeople contains an attribute List<Person> PeopleList;

My difficulty is in how to get a pre-existing List inside of this method to add a new Person to. ListOfPeople temp = new ListOfPeople(x);

I have an error on this line because I have no constructor that takes a ListOfPeople argument. If I were to make it ListOfPeople temp = new ListOfPeople(); then Temp would just call my default constructor where I simply create a new, empty list, and that doesn't allow me to add to a pre-existing list either.

I'm just not sure how I get 'temp' to actually reference my pre-existing list.

Upvotes: 1

Views: 318

Answers (1)

gvaish
gvaish

Reputation: 9404

Use as follows:

public static ListOfPeople operator +( ListOfPeople x, Person y)
{
    ListOfPeople temp = x;
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}

public static ListOfPeople operator +( Person y, ListOfPeople x)
{
    ListOfPeople temp = x;
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}
  • 1st allows you to use: list = list + person
  • 2nd allows you to use: list = person + list

You may also want to overload += operator (non-static) so that you can use list += person

EDIT

Though I solved the problem mentioned. But, then, I agree with others on the operands of '+' being immutable.

Below is update to existing code (assuming ListOfPeople.PeopleList is List<Person>):

public static ListOfPeople operator +( ListOfPeople x, Person y)
{
    ListOfPeople temp = new ListOfPeople();
    temp.PeopleList.addRange(x);
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}

public static ListOfPeople operator +( Person y, ListOfPeople x)
{
    ListOfPeople temp = new ListOfPeople();
    temp.PeopleList.addRange(x);
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}

Upvotes: 1

Related Questions