omar.io

ByteSize

Nov 15, 2013

ByteSize is a utility class that makes byte size representation in code easier by removing ambiguity of the value being represented.

ByteSize is to bytes what System.TimeSpan is to time.

Without ByteSize:

double MaxFileSizeMBs = 1.5;

// I need it in KBs!
var kilobytes = MaxFileSizeMBs * 1024;

With ByteSize:

var MaxFileSize = ByteSize.FromMegaBytes(1.5);

// I have it in KBs!
MaxFileSize.KiloBytes;

ByteSize behaves like any other struct backed by a numerical value.

// Add
var monthlyUsage = ByteSize.FromGigaBytes(10);
var currentUsage = ByteSize.FromMegaBytes(512);
ByteSize total = monthlyUsage + currentUsage;

total.Add(ByteSize.FromKiloBytes(10));
total.AddGigaBytes(10);

// Subtract
var delta = total.Subtract(ByteSize.FromKiloBytes(10));
delta = delta - ByteSize.FromGigaBytes(100);
delta = delta.AddMegaBytes(-100);

Check it out at github.com/omar/ByteSize.