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
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With