My boss has asked me to look into a calculation engine. Effectively, the user will have a table of data that can have calculations be performed on. They will also be able to build their own calculations based on certain restrictions we enforce (the built calculations will then be stored in the database)
Is it possible to call a specific method in C#, dependent upon what is stored in the database? So if the database says, a calculation should perform a standard deviation. When we get that information from the database, is it then possible to call a standard deviation method that we will have in C#?
I hope this is clear.
Considering the small/known amount of operations which will be executed on your data, I would opt to manually code these operations, based on the data retrieved from the database. For extendability/maintainability, it's best to create a proper design for this instead of using a simple switch statement. I'm guessing the Strategy pattern will suit your needs.
As others stated, you could use reflection, to call the methods as specified in the database. The problem with this approach is the data in your database is strongly linked to the method signatures. This is less maintainable than the first approach, but does allow for great extendability with minimal code adjustments. Another downside is using
MethodInfo.Invoke()
is rather slow.If you would opt for reflection, but find the
Invoke()
approach to be too slow, I can recommend this article by Jon Skeet which explains how to convert a MethodInfo into a delegate instance. This gives a major speed boost. I wrote a generic implementation using expression trees for this recently.All in all, it seems like option 1 is still the best for your purposes.