7

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.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • 9
    `public void Pagination(PagerInfo pagerInfo)`? – Oded Feb 24 '13 at 19:14
  • You know, I think you are right. I guess it doesn't work because it's in a cshtml file, and `@helper Pagination(string url, PagerInfo pagerInfo)` fails with the error *Expected a "(" after the helper name.* – Jonathan Wood Feb 24 '13 at 19:17
  • IC - not sure what to do about that. Issue with razor then. See http://stackoverflow.com/questions/4760783/is-it-possible-to-create-a-generic-helper-method-with-razor – Oded Feb 24 '13 at 19:20

1 Answers1

10

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)
{
    // ...
}
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 6
    An interface may be better as it would still allow the class `PagerInfo` to inherit from another class if need be. – jam40jeff Feb 24 '13 at 20:35