Jonathan Wood
Jonathan Wood

Reputation: 67203

How to Accept Generics Argument of Any Type?

Let's say I have a generic class.

public class PagerInfo<T>
{
    // ...
}

And I want to pass an instance of this class to a method in another class.

public void Pagination(PagerInfo pagerInfo)
{
    // ...
}

The method above won't compile because I didn't provide a type argument. But what if I want this method to work regardless of the type. That is, I want this method to operate on a PagerInfo instances regardless of the type. And my method will not access any type-specific methods or properties.

Also, note that my actual method is in an ASP.NET MVC cshtml helper method and not a regular cs file.

Upvotes: 7

Views: 4831

Answers (1)

dtb
dtb

Reputation: 217313

If the method does not access the members of the type that use the generic type parameter, then it's common to define a non-generic base type from which the generic type derives:

public abstract class PagerInfo
{
    // Non-generic members
}

public class PagerInfo<T> : PagerInfo
{
    // Generic members
}
public void Pagination(PagerInfo pagerInfo)
{
    // ...
}

Upvotes: 10

Related Questions