Skip to content

Allow casting bool to int explicitly #32469

@MineCake147E

Description

@MineCake147E

Sometimes I need to convert bool values into some kind of integral type(such as uint) like:

public static int U(int y) => y > 0 ? 1 : 0;

which currently generates (on SharpLab x64 Release)

C.U(Int32)
    L0000: test ecx, ecx
    L0002: jg L0007
    L0004: xor eax, eax
    L0006: ret
    L0007: mov eax, 0x1
    L000c: ret

while

public static bool G(int y) => y > 0;

becomes

C.G(Int32)
    L0000: test ecx, ecx
    L0002: setg al
    L0005: movzx eax, al
    L0008: ret

I need both codes compiles into same code as G(that uses setg instruction instead of jg).

Proposal

By allowing conversion from bool to int like:

public static int U(int y) => (int)(y > 0);

it can be compiled into

C.U(Int32)
    L0000: test ecx, ecx
    L0002: setg al
    L0005: movzx eax, al
    L0008: ret

Metadata

Metadata

Assignees

No one assigned

    Labels

    untriagedNew issue has not been triaged by the area owner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions