Reputation: 11
So i'm trying to make a static class called ActionExtensions which has a body like this:
public static class ActionExtensions {
public static IContainer Add<TObjectType>(this IContainer container, TObjectType obj) {
return container;
}
}
and uses interface IContainer. I also have a class called Student with list of grades:
public class Student, IContainer {
public IList<int> Grades{ get;set;}
}
Now I want to do something like this:
var student = new Student();
student.Add(3); //adding grade 3 to list of student's grades
But i don't want to define an Add method to a Student class. Rather use my method from ActionExtensions. Is this even possible?
Upvotes: 1
Views: 432
Reputation: 101
It is possible. You could do it like this:
public interface IContainer<T>
{
IList<T> Values { get; }
}
public static class ContainerExtensions
{
public static void Add<T>(this IContainer<T> container, T value) =>
container.Values.Add(value);
}
public class Student : IContainer<int>
{
public List<int> Grades { get; set; }
IContainer<int>.Values => Grades;
}
You can than use it like this
var student = GetSomeStudent();
student.Add(3);
Upvotes: 1