Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Accept Generics Argument of Any Type?

Tags:

c#

generics

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.

like image 313
Jonathan Wood Avatar asked Feb 24 '13 19:02

Jonathan Wood


People also ask

Which types can be used as arguments of a generic type?

The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).

How do you define a class which accepts a generic type parameter?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

Can generics take multiple type parameters?

A Generic class can have muliple type parameters.

Which parameters is used for a generic class to return and accept any type of object?

Which of these type parameters is used for a generic class to return and accept any type of object? Explanation: T is used for type, A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.


1 Answers

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)
{
    // ...
}
like image 55
dtb Avatar answered Nov 03 '22 00:11

dtb