Is it possible to declare two interdependent classes each in a separate file?

Viewed 73

I have two PowerShell classes that are inter-dependent:

Class A:

class A {

   [int] hidden $i
   [B]   hidden $b_

   A([int] $i) {
     $this.i = $i
   }

   [void] set_b([B] $b) {
      $this.b_ = $b
   }

   [B] get_b() {
      return $this.b_
   }

   [int] get_i() {
      return $this.i
   }
}

and class B:

class B {

   [int] hidden $j
   [A]   hidden $a_

   B([int] $j) {
     $this.j = $j
   }


   [void] set_a([A] $a) {
      $this.a_ = $a
   }

   [A] get_a() {
      return $this.a_
   }

   [int] get_j() {
      return $this.j
   }
}

If I put both classes into the same source file, A-and-B.ps1, and dot-source the file:

. .\A-and-B.ps`

I am able to use these classes:

[A] $a = new-object A 42
[B] $b = new-object B 99

$b.set_a($a)
$a.set_b($b)

$a.get_b().get_a().get_i()

However, I want to put each class into its own file: A.ps1 and B.ps1. Unfortunately, I cannot dot-source A.ps1 because I receive Unable to find type [B]. error messages (which I understand).

So I tried to forward-declare class B in A.ps1:

class B {}

class A {
   ...

which allowed to dot-source both files, A.ps1 and B.ps1.

However, trying to use these classes results in the error message

Cannot convert argument "b", with value: "B", for "set_b" to type "B": "Cannot convert the "B" value of type "B" to type "B"."

So, is there a way to put interdependent classes into their own source file in PowerShell?

0 Answers
Related