Search code examples
c#binaryreader

Cannot implicitly convert type 'int' to LittleEndian ByteOrder


I have a problem with my function for loading RAW images. I don't understand the reason for the error. It shows me this error:

Cannot implicitly convert type 'int' to 'Digital_Native_Image.DNI_Image.Byteorder'

public void load_DNI(string ficsrc)
{
    FileStream FS = null;
    BinaryReader BR = null;
    int width = 0;
    int height = 0;
    DNI_Image.Datatype dataformat = Datatype.SNG;
    DNI_Image.Byteorder byteformat = Byteorder.LittleEndian;

    FS = new FileStream(ficsrc, System.IO.FileMode.Open);
    BR = new BinaryReader(FS);

    dataformat = BR.ReadInt32();
    byteformat = BR.ReadInt32();
    width = BR.ReadInt32();
    height = BR.ReadInt32();

    // fermeture des fichiers
    if ((BR != null))
        BR.Close();
    if ((FS != null))
        FS.Dispose();

    // chargement de l'_image
    ReadImage(ficsrc, width, height, dataformat, byteformat);
}

Solution

  • int's cannot be implicitly converted to enum's. You need to add explicit casts here:

    dataformat = (Datatype.SNG)BR.ReadInt32();
    byteformat = (Byteorder)BR.ReadInt32();
    

    Read Casting and Type Conversions (C# Programming Guide) for more information.

    However, note that the if (BR != null) check is not necessary, and this is really not the right way to handle IDisposable objects. I'd suggest you rewrite this code to use using blocks. This will ensure that FS and BR get disposed properly:

    int width;
    int height;
    Datatype dataformat;
    Byteorder byteformat;
    
    using (var FS = FileStream(ficsrc, System.IO.FileMode.Open))
    using (var BR = new BinaryReader(FS))
    {
    
        dataformat = (Datatype.SNG)BR.ReadInt32();
        byteformat = (Byteorder.LittleEndian)BR.ReadInt32();
        width = BR.ReadInt32();
        height = BR.ReadInt32();
    }
    
    // chargement de l'_image
    ReadImage(ficsrc, width, height, dataformat, byteformat);
    

    But it also seems like you can improve this more by refactoring the ReadImage method to use the same BinaryReader. Then you could rewrite this method to look more like this:

    using (var FS = FileStream(ficsrc, System.IO.FileMode.Open))
    using (var BR = new BinaryReader(FS))
    {
    
        var dataformat = (Datatype.SNG)BR.ReadInt32();
        var byteformat = (Byteorder.LittleEndian)BR.ReadInt32();
        var width = BR.ReadInt32();
        var height = BR.ReadInt32();
        ReadImage(ficsrc, width, height, dataformat, byteformat, BR);
    }