Calculator Calculation With A Single Line Of Code In C#

This blog is applicable on almost all platforms, whether it is the web or Windows.
 
Calculation is an integral part of any application. When we talk about creating applications having a rich user interface with all the necessary features, it becomes time-consuming and lengthy to implement that.
 
The basic calculator application requires logic and algorithms to perform such arithmetic operations; even implementing from open source projects takes a bit of time. Those who are familiar with offline architecture (DataTable) might be aware of the compute function.
 
How exciting is it when we say this can be done using a single line of code!
 
Excited??
 
 
We have been using formulas in MS Excel and there we can see all the calculations are done in a single line of code whether it is SUM, COUNT, AVG etc. For example:
 
=SUM(2+3)
 
Let's dig into the example to see how we can create this without using long lines of code. 
 
Namespace required
 
System.Data 
  1. var expression = "2+3";  
  2. var result = new DataTable().Compute(expression,"")+"";  
Output
 
5 (expected :))
 
Let's try some other calculations.
  1. var expression = "2 + 3(5*3/2)";    
  2. var result = new DataTable().Compute(expression,"")+"";    
Output
 
24.5
 
Note
An empty string has been concatenated at the end of the line to keep yourself on the safe side.
 
Compute function is not only capable of doing basic operations like sum, multiplication, division, subtraction but it can also perform power, square root, and much more than that.
 
By just allowing the user to write their own expression on a textbox, we can get the output right there without any hassle.
 
Conclusion
 
We can implement this single line for allowing the users to do calculations in the application with a minimal line of code.
 
I hope you enjoyed reading this blog. Stay connected to C# Corner for more updates.
Next Recommended Reading How To Call C# If Else In A Single Line