Search code examples
c#ffmpegaforge

Why does the compiler convert bool to integer and back to bool instead of returning the bool itself?


I was reading VideoFileWriter class from AForge.Video.FFMPEG assembly via ILSPY (I was interested to see how a particular method works) and found this:

public bool IsOpen {
    [return: MarshalAs(UnmanagedType.U1)]
    get {
        return ((this.data != null) ? 1 : 0) != 0;
    }
}

What's the reason to do that bool to integer than back to bool conversion rather just do this.data != null?


Solution

  • It is decompiled code, it is likely just a glitch of the decompiler.


    After thinking for a bit, here is a reasonable implementation that may potentially turn in to the same compiled code

    public enum ConnectionState
    {
        Closed = 0,
        Open = 1,
        Opening = 2,
        OtherStuff = 3,
        AndSoOn = 4,
    }
    
    public bool IsOpen
    {
        get
        {
            ConnectionState state;
            if (this.data != null)
            {
                state = ConnectionState.Open;
            }
            else
            {
                state = ConnectionState.Closed;
            }
    
            return state != ConnectionState.Closed;
        }
    }