I have just been looking through some old code, and found a classic method that most people will use at some point;
public static int CalculatePercentage(int done, int total)
{
return (done * 100) / total;
}
Now, I gots a thinking... Instead of using a method (or indeed a property) for this type of "expression", why not use the C# 3.0 Expression Tree functionality? So just for a larf I came up with;
Expression<Func<int, int, int>> percentage = (done, totalCount) => ((done * 100) / totalCount);
The problem here is that in order to use the expression tree I have to call Compile() on the expression before invoking it.
Expression<Func<int, int, int>> percentage = (done, totalCount) => ((done * 100) / totalCount);
var completed = percentage.Compile()(3, 15);
So in this case, I think using an Expression is a little overkill. So I opted to have a static Func<> in a static class; (some may argue expressing this as a Func<T,K> rather than the original method may be overkill, but I think its cool ;) ).
class SimpleFunctions
{
public static readonly Func<int, int, int> CalculatePercentage = ((done, totalCount) => ((done * 100) / totalCount));
}
Again, its down to personal preference. This is just an example of using the Func<> class instead of creating a method to do a specific job. And working out a percentage isn't exactly a taxing calculation, but you get the idea ;).
Full Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Samples.ExpressionTrees
{
class Program
{
static void Main(string[] args)
{
int total = 15;
for (int done = 0; done < total; done++)
{
Console.WriteLine(string.Format("{0} out of {1} done -- {2}% Complete", done, total, SimpleFunctions.CalculatePercentage(done, total)));
}
}
}
class SimpleFunctions
{
public static readonly Func<int, int, int> CalculatePercentage = ((done, totalCount) => ((done * 100) / totalCount));
}
}
Output
Refrences
http://davidhayden.com/blog/dave/archive/2006/12/21/BuildExpressionTreesTutorialAndExamples.aspx
No comments:
Post a Comment