Home > database >  Does C# have a generic equivalent of Java's Class<T>?
Does C# have a generic equivalent of Java's Class<T>?

Time:09-23

In Java, Class<T> is generic, which is useful if I want a constrained parameter; for example:

public void foo(Class<? extends Comparable<?>> clazz) {
    ...
}

foo(Integer.class) // OK!
foo(Object.class) // Error - does not implement Comparable<?>

C#'s equivalent is Type, but it's not generic, meaning you can't constrain parameters; for example:

public void Foo(Type clazz) {
    ...
}

Foo(typeof(int)) // OK!
Foo(typeof(object)) // OK!

I guess one solution could be to pass the type as a generic parameter; for example:

public void Foo<T>() where T : IComparable<T> {
    typeof(T)
}

Foo<int>() // OK!
Foo<object>() // Error - does not implement IComparable<T>

Is this the only approach, or is there something more equivalent to the Java approach, in other words is there something like Type<T> in C#?

CodePudding user response:

Foo<T>() approach is the only one in C#.

Java approach is a workaround for compile-time-only (type erasure) generics.

CodePudding user response:

You can do public Foo<T>(T inputParam) where T: IComparable, new() and limit the type of generic inputParam. However, you can only limit it by an interface and not by class. More Info

  • Related