Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a method of IEnumerable type that takes in generic type

I created an IEnumerable method that takes in an IEnumerable of type PERSON which swaps the first names and last names of the employee (They are currently adding them into a database in a single field ("John Smith", "Craig Robertson") etc.

I have another IEnumerable called ProjectPerson which has similar but different data that I would like to swap the first and last names of as well.

Both IEnumerables have "Name" as a field so the code works fine for both, I just want to be able to re-use this code without creating an overload with IEnumerabe<Person> and another with IEnumerable<ProjectPerson> but the same code inside each.

Is there a way to set up an IEnumerable method that can be used by different Types? Maybe passing in the Type as an argument then cast?

I have created an interface called IPerson:

    public interface IPerson
    {
        string Name { get; set;}
    }

and I have the following:

public class Person: IPerson {..}

public class ProjectPerson: IPerson {..}

My Method looks like this:

private void IEnumerable<IPerson> SwapFirstAndLastNames(IEnumerable<IPerson> persons)
{
    foreach (var employee in persons)
    {
        //do the swapping
    }
    return persons;
}

I am calling this method elsewhere in the class using these two lines:

_projectPerson = SwapFirstAndLastNames(projectpersons) 

_person = SwapFirstAndLastNames(person);

Using the above I get an error on that method saying "Cannot convert from ProjectPerson to IPerson (same with Person to IPerson) and also "The best overload method match for SwapFirstAndLastNames(IEnumerable) has some invalid arguments.

Both person and projectPerson are of type IENumerable (as are the underlined ones) and the data used in each is used elsewhere to fill datagrids and such like. So i'm basically looking for a single method that takes any type of IEnumerable, swaps the IEnumerable.Name field around (i've got the code to do this already) and then returns the swapped IEnumerable data. I have this working on a single Type.

like image 260
iandavidson1982 Avatar asked Jan 14 '14 09:01

iandavidson1982


1 Answers

You need to use the following syntax to define the method.

private void IEnumerable<T> SwapFirstAndLastNames(IEnumerable<T> persons) where T : IPerson
{
    foreach (var employee in persons)
    {
       //do the 
    }
    return persons;
}

Note the where T : IPerson this constrains your method so it can only be called by classes which implement this interface (you wouldn't want someone to pass ints in for example!). You'd implement this interface which both ProjectPerson and Person and include all the fields your method needs to run (presumably firstname/lastname).

The interface would look something like

public interface IPerson
{
  Firstname {get;set;}
  Lastname {get;set;}
}
like image 161
Liath Avatar answered Oct 04 '22 12:10

Liath