Search code examples
c#.netienumerable

Method for class list object


I know this is a bit odd and I do know another way to work around this but I was wonder if it is possible to have a method that would affect a list of itself. I'll explain.

This would be my workaround

public class Example
{
    public void Sanitize()
    {
        // Does logic sanitize itself using API
    }

    public static List<Example> Sanitize(List<Example> examples)
    {
        /// returns a list of sanitized Examples
    }
}

How the Example would be able to work on its own.

// Base Example sanitized
Example example = new Example(...);
example.Sanitize();

What I would also like to do

// Whole list sanitized
List<Example> examples = new List<Example> {...};
examples.Sanitize();

Is there a way to do that instead of being required to do this?

List<Example> startingExamples = new List<Example> { ... }
List<Example> endingExamples = Example.Sanitize(startingExamples);

Solution

  • Looks like you could use an extension method.

    Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type. For client code written in C#, F# and Visual Basic, there's no apparent difference between calling an extension method and the methods defined in a type.

    An extension method is a static method on a static class that is visible to the code that is using it. For example, public code. The first parameter of the method is the type that the method operates on and must be preceded with the this modifier.

    So, for example, you could do something like this...

    public static class EnumerableOfExampleExtensions
    {
        public static void Sanitize(this IEnumerable<Example> examples) /*or List is fine*/
        {
            // Null checks on examples...
            foreach (var example in examples)
            {
                example.Sanitize();
            }
        }
    }
    

    Then you can call it as an instance method on any IEnumerable<Example>.

    List<Example> examples = new List<Example>();
    examples.Sanitize();