How do I check what is the type passed as type parameter for a generic method?
foo<T>() {
// What type is T?
// I want to able to do something like,
// if T is String do something, if T is int do something else.
}
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.
Definition: “A generic type is a generic class or interface that is parameterized over types.” Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.
The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).
You can use the equality (==
) operator in the latest Dart SDK versions:
foo<T>() {
if (T == String) {
} else if (T == int) {
}
}
One thing that's not trivial to do is inspect generic types, however:
foo<T>() {
// Invalid syntax.
if (T == List<String>) {}
}
In that case, you'll want more specialized methods:
fooOfT<T>(List<T> list) {
if (T == String) {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With