Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identity Operator / Comparison without Implicit Type Conversion

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.

like image 590
JohnLBevan Avatar asked Jun 16 '17 10:06

JohnLBevan


People also ask

How is implicit conversion different from explicit?

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.

What is implicit type conversion?

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.

What is implicit conversion give an example?

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.


1 Answers

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.

like image 75
user4003407 Avatar answered Oct 24 '22 04:10

user4003407