This is a good candidate for a simple Interpreter .
Code like this is a simple start, you will need to handle perhaps more cases and take into account differences in the package (e.g. Gb vs Gb ).
You start by defining the context and expression:
public class FileSizeContext { private string input; private long output; public FileSizeContext(string input) { this.Input = input; } public string Input { get; set; } public long Output { get; set; } } public abstract class FileSizeExpression { public abstract void Interpret(FileSizeContext value); }
Then you define your terminal expression and all options:
public abstract class TerminalFileSizeExpression : FileSizeExpression { public override void Interpret(FileSizeContext value) { if(value.Input.EndsWith(this.ThisPattern())) { double amount = double.Parse(value.Input.Replace(this.ThisPattern(),String.Empty)); var fileSize = (long)(amount*1024); value.Input = String.Format("{0}{1}",fileSize,this.NextPattern()); value.Output = fileSize; } } protected abstract string ThisPattern(); protected abstract string NextPattern(); } public class KbFileSizeExpression : TerminalFileSizeExpression { protected override string ThisPattern(){return "KB";} protected override string NextPattern() { return "bytes"; } } public class MbFileSizeExpression : TerminalFileSizeExpression { protected override string ThisPattern() { return "MB"; } protected override string NextPattern() { return "KB"; } } public class GbFileSizeExpression : TerminalFileSizeExpression { protected override string ThisPattern() { return "GB"; } protected override string NextPattern() { return "MB"; } } public class TbFileSizeExpression : TerminalFileSizeExpression { protected override string ThisPattern() { return "TB"; } protected override string NextPattern() { return "GB"; } }
Then you add a nonterminal expression (this does the bulk of the work):
public class FileSizeParser : FileSizeExpression { private List<FileSizeExpression> expressionTree = new List<FileSizeExpression>() { new TbFileSizeExpression(), new GbFileSizeExpression(), new MbFileSizeExpression(), new KbFileSizeExpression() }; public override void Interpret(FileSizeContext value) { foreach (FileSizeExpression exp in expressionTree) { exp.Interpret(value); } } }
Finally, here is what the client code is:
var ctx = new FileSizeContext("10Mb"); var parser = new FileSizeParser(); parser.Interpret(ctx); Console.WriteLine("{0} bytes", ctx.Output);
Real-time example: http://rextester.com/rundotnet?code=WMGOQ13650
edits. Changed for MB from Mb (one officially MegaByte another - MegaBit). The int value has been changed to accommodate large sizes.