Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking what type is passed into a generic method

Tags:

dart

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.
}
like image 678
Ikhwan Avatar asked May 05 '18 11:05

Ikhwan


People also ask

How do you find the type of generic type?

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.

How does a generic method differ from a generic type?

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.

What is generic type of data?

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.

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).


1 Answers

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) {

  }
}
like image 164
matanlurey Avatar answered Nov 25 '22 03:11

matanlurey