Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method on parameter of generic type

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?

like image 401
AMK Avatar asked Jan 18 '26 16:01

AMK


1 Answers

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.

like image 125
O. R. Mapper Avatar answered Jan 21 '26 06:01

O. R. Mapper