Redscript
HomeGitHubDiscord
  • Home
  • Getting Started
    • Downloads
    • Setup for VSCode
    • Setup for JetBrains IDEs
    • How to start REDscripting
      • Step 1: Mod structure
      • Step 2: Finding the right class
  • Language
    • Intro
      • REDscript in 2 minutes
      • How to create a hook
        • Things to hook
    • Language Features
      • Intrinsics
      • Loops
      • Strings
      • Modules
      • Annotations
      • Conditional compilation
      • Configurable user hints
    • Built-in Types
    • Built-in Functions
      • Math
      • Random
      • Utilities
  • References and examples
    • Common Patterns
      • Safe downcasting
      • Class constructors
      • Hash maps
      • Heterogeneous array literals
      • Scriptable systems (singletons)
      • DelaySystem and DelayCallback
      • Generic callbacks
      • Persistence
    • Logging
    • UI Scripting
      • Logging Widget Trees
      • Popups
    • Vehicle system
    • Weapons
    • Codeware callbacks
      • Scriptables comparison
    • Libraries
    • Gameplay
      • Sleeping and Skipping Time
  • Help
    • Community
    • Troubleshooting
Powered by GitBook
On this page
  1. References and examples
  2. Common Patterns

Safe downcasting

PreviousCommon PatternsNextClass constructors

Last updated 10 months ago

Was this helpful?

CtrlK

Was this helpful?

The as operator returns null when a dynamic cast fails. You can use it combined with IsDefined to perform safe downcasts. The following example shows how you can safe downcast a VehicleObject to a WheeledObject, a CarObject or a BikeObject:

let vehicle: ref<VehicleObject>;

let wheels = vehicle as WheeledObject;
if IsDefined(wheels) {
  // vehicle is known to be a WheeledObject.
}

let car = vehicle as CarObject;
if IsDefined(car) {
  // vehicle is known to be a CarObject.
}

let bike = vehicle as BikeObject;
if IsDefined(bike) {
  // vehicle is known to be a BikeObject.
}

as operator will keep the same kind of reference, that is ref<T> to ref<U> and wref<T> to wref<U>.