Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new method to List<T> over object from which is made of

Tags:

methods

c#

Is there way to add new method to List object over the object from which it's made of .In other word can class be written in such way ,when List is made from it that it adds new method to that List. Here's an exemple:

class Employee
{
    public int age;
    public Employee(int age)
    {
         this.age = age;
    }
    //some more code here...
}

And then:

List<Employee> sector01 = new List<Employee>(){new Employee(22), new Employee(35)};
sector01.OutputAll(); //Adds method like this
like image 213
Miro Avatar asked Sep 19 '25 01:09

Miro


2 Answers

You could define it as an extension method:

namespace SomeNamespace
{
    public static class ListExtensions
    {
        public static void OutputAll(this IEnumerable<Employee> employees)
        {
            foreach (var employee in employees)
            {
                Console.WriteLine("{0}: {1}", employee.FirstName, employee.LastName);
            }
        }
    }
}

and then simply bring the namespace where this static class is defined into scope:

using SomeNamespace;

and now you will be able to do this:

List<Employee> sector01 = new List<Employee>()
{
    new Employee(22), 
    new Employee(35)
};
sector01.OutputAll();
like image 52
Darin Dimitrov Avatar answered Sep 21 '25 15:09

Darin Dimitrov


What you're talking about is an extension method. You can write them in C# 3.0 and above.

You have to write a static class to contain your extension methods, although they needn't all be inside the same class. Then you can use them much as if they were in the initial class definition.

Like this:

public static class ListExtensions
{
    public static void OutputAll<T>(this List<T> list)
    {
        //do something
    }
}

Then your calling code can go anywhere that has access to the ListExtensions class:

List<Employee> sector01 = new List<Employee>(){new Employee(22), new Employee(35)};
sector01.OutputAll();

As you can see, the code to call OutputAll is just as you expected.

like image 41
Justin Morgan Avatar answered Sep 21 '25 14:09

Justin Morgan