Why does an implicit conversion to [byte]
work, but when replacing byte
by bool
it no longer works?
I. e. the following works...
Add-Type -TypeDefinition @'
public readonly struct MyByte
{
private readonly byte value;
public MyByte( byte b ) => this.value = b;
public static implicit operator byte( MyByte b ) => b.value;
public static explicit operator MyByte( byte b ) => new MyByte( b );
public override string ToString() => $"{value}";
}
'@
[byte] $d = [MyByte]::new( 1 ) # OK
...while this very similar code does not:
Add-Type -TypeDefinition @'
public readonly struct MyBool
{
private readonly bool value;
public MyBool( bool b ) => this.value = b;
public static implicit operator bool( MyBool b ) => b.value;
public static explicit operator MyBool( bool b ) => new MyBool( b );
public override string ToString() => $"{value}";
}
'@
[bool] $b = [MyBool]::new( $true ) # Error
This produces the following error:
Cannot convert value "MyBool" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0.
Note that in C# the implicit conversion to bool
works as expected:
public class MyBoolTest {
public static void Test() {
bool b = new MyBool( true ); // OK
}
}
So this seems to be a PowerShell issue only.
(PSVersion: 7.2.2)