BinaryReader is a class that reads primitive data types as binary values in a specific encoding (see MSDN for more details). The usage of this class is to read sequences of bytes usually created by reading a file, getting data from sockets and retrieving data from memory. After having the stream of bytes, we may want to convert these data to other primitive types such as: integer, boolean, char, double, float, …

Indeed, there are many read methods like: ReadInt32, ReadInt64, ReadBoolean, ReadChar, ReadDouble. But hey, where is the ReadFloat method ?? The simple answer is: ReadSingle. The Single value type represents a single-precision 32-bit number which is the float we were looking for.

I must admit that I didn’t think that this is an issue that worth a post in this blog. My mind was changed after I saw 2 colleagues struggling with the BinaryReader, trying to find some weird workarounds to the “missing” ReadFloat method (they were trying to read doubles instead…). So, maybe it is not such a bad idea to mention this issue.

Lets take it a little step further and use Extension Methods to add the “float” type to the BinaryReader class so we avoid the confusion:

static class BinaryReaderExtension
    public static float ReadFloat(this BinaryReader br)
        return br.ReadSingle();

Now we can do the following:

BinaryReader br = new BinaryReader(File.Open(@"c:\stream.txt", FileMode.Open));
float value = br.ReadFloat();

Hope you enjoyed, that’s all for now.

Tags :

2 Responses to “Where is my BinaryReader.ReadFloat ?”

  1. Ron

    Said on April 4, 2008 :

    I have to admit, I’m a bit wary of adding an extension method simply to change the name of an existing function. This seems like an abuse of the extension method system and can lead to some ugly code, and bewildered coders who wonder where ReadFloat went as soon as they switch to a different project.

  2. Shahar Y

    Said on April 4, 2008 :

    I totally agree that the use of extension method here is not justified, it was just for “fun”.
    About those “bewildered coders who wonder where ReadFloat went as soon as they switch to a different project” – this is true for all extension methods in general…

Post a Comment