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);
You can have your static method iterate and mutate the list elements in place.
public class Example
{
public void Sanitize()
{
// Does logic sanitize itself using API
}
public static void Sanitize(List<Example> examples)
{
foreach (var example in examples)
{
example.Sanitize();
}
}
}
Note that you cannot modify the list itself while iterating it, but you can make changes to the elements of the list.
You can use an extension method to add functionality to the list.
static class ExtensionMethods
{
public static void Sanitize(this List<Example> source)
{
foreach (var item in source) item.Sanitize();
}
}
Now you can do this:
var list = new List<Example>();
list.Sanitize();
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();