tryGet<R extends Object?> method

R? tryGet<R extends Object?>()

Attempts to read the value stored in this VARIANT as type R.

This method is non-throwing and returns null if:

This is intended for defensive or exploratory access to loosely typed VARIANT values.

Example:

final variant = Variant.from('Hello, World!');
final str = variant.tryGet<String>();
if (str != null) {
  print(str);
}

Implementation

R? tryGet<R extends Object?>() {
  final result = switch (vt) {
    VT_EMPTY || VT_NULL => null,
    VT_BOOL => boolVal,
    VT_BSTR => bstrVal.isNull ? null : bstrVal.toDartString(),
    VT_I1 => cVal,
    VT_I2 => iVal,
    VT_I4 => intVal,
    VT_I8 => llVal,
    VT_UI1 => bVal,
    VT_UI2 => uiVal,
    VT_UI4 => uintVal,
    VT_UI8 => ullVal,
    VT_R4 => fltVal,
    VT_R8 => dblVal,
    VT_DISPATCH => pdispVal,
    VT_UNKNOWN => punkVal,
    _ => null,
  };

  return result is R ? result : null;
}