When using PowerShell, occasionally we compare objects of different types. A common scenario being $int -eq $bool
(i.e. where 0 -eq $false
, 0 -ne $true
, and any non-zero value only equals true, but not false).
Mostly that's a good thing; sometimes it's a pain (e.g. if I'm looking for all properties on an object which have value 1
, but I don't want all those which have value $true
).
Question
Is there an operator which performs this comparison without conversion; i.e. which essentially does the same as JavaScript's identity operator (===
);?
Bonus Question
If there is such an operator, is there any tolerance? i.e. whilst I don't want to treat 1
and true
as being identical, it would (sometimes) be helpful if I could treat [int]1
and [long]1
as though they are.
Implicit conversion is the conversion in which a derived class is converted into a base class like int into a float type. Explicit conversion is the conversion that may cause data loss. Explicit conversion converts the base class into the derived class.
Implicit type conversion in C language is the conversion of one data type into another datatype by the compiler during the execution of the program. It is also called automatic type conversion.
Implicit conversions: No special syntax is required because the conversion always succeeds and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
PowerShell do not offer such operator directly, but you can use standard .NET method [Object]::Equals
to do such comparison.
Note:
It allows to types to implement they own equality comparison by overriding virtual Object.Equals
method, thus it possible to have some weird behavior, if some custom type implement it improperly. But all standard .NET types should fine and consider themselves equals only to the instance of the same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With