I want to write a generic method that as input has a list of generic objects. I want to call a method on each of the list items.
What I'm trying to do is writing something like:
public void ResetPointProperties<T> (List<T> Points)
{
foreach (T point in Points)
{
point.Reset();
}
}
How can I call Reset() on my list items?
You are almost there. However, what is missing is that as it stands, the compiler does not know whether/that each T has a reset() method. Therefore, you will have to add a constraint to the T parameter that requires T to implement an interface or inherit from a class that declares such a reset() method.
For instance, let's assume you somewhere have the following interface:
public interface IThing
{
void reset();
}
Then, you could declare your above method as follows:
public void ResetPointProperties<T> (List<T> Points)
where T : IThing
This enforces that any type passed to the T type parameter must implement IThing. In return, the compiler can guarantee that point in your method actually has a reset() method that you can invoke.
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