tryCast<U> method

U? tryCast<U>()

Casts the receiver to U when its runtime type matches, otherwise returns null.

Unlike the as operator this never throws; a null receiver (or any value that is not a U) yields null.

Example:

Object? value = 'hi';
value.tryCast<String>(); // 'hi'
value.tryCast<int>();    // null

Implementation

U? tryCast<U>() {
  final o = this;
  if (o is U) return o;
  return null;
}