$App = New-Object -TypeName Microsoft.SqlServer.Dts.Runtime.Application;
$PackageFullPath = 'C:\SSISPackage.dtsx';
$Package = $App.LoadPackage($PackageFullPath, $null, 0);
$x = $Package.Connections
$x.Remove("Something")
$App.SaveToXml($PackageFullPath, $Package, $null)
My question is when I assign the instance to a new variable $x
, how do I know when I call a method on $x
that it will reflect on $Package
? So when I remove someting from $x
, will it also remove that thing from $Package
? If the answer is "it depends" how can I know without setting up an experiment?
CodePudding user response:
tl;dr
Because the $Package.Connections
property contains an instance of a .NET reference type, namely Microsoft.SqlServer.Dts.Runtime.Connections
, $x
and $Package.Connections
reference the very same collection instance, so $x.Remove("Something")
is the same as $Package.Connections.Remove("Something")
The behavior depends on whether a given value is an instance of a .NET reference type or value type:
When reference-type instances are assigned to a (new) variable / passed as an argument, it is the reference ("pointer") to the actual data that is copied, which means that both the original value and the target variable / parameter refer to the same object.
By contrast, assigning / passing a value-type instance makes a copy of the value itself, resulting in independent copies of the data.
You can examine an object stored in a given variable $x
as follows: $true
indicates a value-type instance, $false
a reference-type instance:
$x.GetType().IsValueType
Note that collection-like types, including arrays, are reference-type instances, so $x
and $Package.Connections
in the code in your question will refer to the same collection.
By contrast, all so-called primitive types, such as numbers, are value types.
If you don't want to rely on inspection at runtime, you can examine the documentation for a given type, which (with the language set to C#) will use the following "type-kind" identifiers:
- Reference types:
class
(e.g.ArrayList
)
- Value types:
struct
(e.g.,DateTime
)enum
(e.g.,PlatformID
)