Skip to content
Nubgrammer
Menu
  • Home
  • Contact Me
Menu

How to build a Simple Calculator in C#

Posted on October 24, 2017September 24, 2018 by Tyler Sells

TL;DR:

Here’s the code: GitHub: Simple Calculator

The video is down below.

What are we doing this time?

I’m glad you asked.  We’re going to write a simple calculator app.  Why you ask?  Because it’s a good introduction to a lot of the tools within VS (Visual Studio) and it means that I can shorten the length of the other videos in the RSS Aggregator series.  That’s kind of a win-win right?

Video time:

Here’s the video:

… and here’s the code.

It’s really not that bad, I promise

Ok, it’s a ~35 minute video, but there’s really nothing too difficult in there.  What I really wanted to focus on in this one was navigating through the work space.  I’ll be honest with you, once we get into the Web App stuff, you’ll probably want to MVC land and won’t need the WinForms stuff anyway.  However, doing simple projects like this will make you much more comfortable within VS and it will help reduce the learning curve for MVC Web Apps.

You’ll notice that Visual Studio is, unsurprisingly, very visual when it comes to creating a desktop app.  This makes building any sort of GUI (Graphical User Interface) really easy, once you figure out where everything is.  For that part, just watch the video.  I mean, I could tell you to move your mouse to the left-hand side of the screen, about 2/3rds of the way up, click on Toolbox, open All Windows Forms, click and drag the control over but that would get as confusing for me to write as it would for you to follow along.

The Meaty Bits:

The Operator class

class Operator
{
    private char op;
    public Operator(char op)
    {
        this.op = op;
    }
    public double apply(double before, double after)
    {
        double b = before;
        switch (op)
        {
            case '-':
                b -= after;
                break;
            case '+':
                b += after;
                break;
            case '*':
                b *= after;
                break;
            case '/':
                b /= after;
                break;
            default:
                break;
        }
        return b;
    }
}

The important part about this class is the apply method.  In a nutshell, all we are doing is getting the value of the number before we make the change, figuring out which operation we need to do, and then combining the before number with the after number using that operation.  Using this method, you could actually create your own operators and do whatever you want.  You would only have to add a case for the custom operator, add a button for it on the calculator GUI, and there you have it.

Haven’t seen a switch statement before?  That’s ok!  Here’s what it does:

//Looks like we need a switch statement for
//a variable.  In this case, op.
switch (op)
{
    //Is this the case where op = '-'?
   case '-':
        //Let's do this to the b variable then
        b -= after;
        //Ok, now we're done.  Let's break
        //on through to the other side.
        break;
    //op wasn't '-'? Ok, is it a '+'?
    case '+':
        //Let's do this if it is: 
        b += after;
        break;
    //so on and so forth:
    case '*':
        b *= after;
        break;
    case '/':
        b /= after;
        break;
    //Wait!  None of our cases matched.
    //Ok, lets just break out by default then
    default:
        break;
}

Make sense?
This one’s beef:

private void UpdateTextBox(string str, TextBox tb)
{
    tb.Text = str;
}
private double ConvertToDouble(string str)
{
    return Double.Parse(str);
}

Why did I do it this way?  Yes, both of these functions hardly do anything and aren’t necessary.  However, if you wanted to add further functionality in regards to how the TextBox control is updated or how the numbers are converted, you only have to change these functions.  This is an over simplified example of functional programming.  I built functions to do a single, simple task and made it as good at that task as possible.  I might cover functional programming in another post someday, but for the scope of this one, I figured I would scratch the surface.

Now the other white meat:

private string solve()
{
    double before = numbers[0];
    for (int i = 1; i < this.numbers.Count; i++)
    {
        before = ops[i - 1].apply(before, numbers[i]);
    }
    return before.ToString();
}

This is the function that brings it all together.  I sort of explained it in the video but I’ll try to explain it a little better here.  The thought process is that you have to start with the first number the user pushed in.  Then, you need to loop through the rest of the numbers and apply the correct operator after each number.  We start our increment at 1 because numbers[0] has already been spoken for.  this.numbers.Count is a built-in property of any List instance and it tells use how many numbers there are for us to count up.  Because our operators DO start at ops[0] when it’s time to look at those, we have to account for that 1 increment offset at the beginning of the loop.  If you wanted to test this, you could make the op variable inside your operator class public, and then call MessageBox.Show(before+"_"+ops[i-1].op +"_"+numbers[i]); inside the loop to verify that the operators are getting applied in the correct order.  At any rate, I would be happy to answer any other questions about this.  Just post a comment somewhere, anywhere.

Final Thoughts on the Calculator:

Thanks for reading, and remember, this is a SIMPLE Calculator.  There are still a couple of bugs in it and it could use quite a few more features, but hopefully this has given you enough information to dig in and implement some new things on your own.  Challenges are fun right?

Author: Tyler Sells

Github

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • More
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to email a link to a friend (Opens in new window) Email
  • Click to share on Reddit (Opens in new window) Reddit

Like this:

Like Loading...

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Follow me on Twitter

My Tweets

Github Repos

vtsells (Tyler Sells)

Tyler Sells

vtsells
http://www.nubgrammer.com
Joined on Jun 21, 2017
9 Public Repositories
100DaysOfCode
embers
MultiSelect
MVC-Project-Start
nubgrammer.com
PermIT
Spray
vtsells.github.io
Wizard
0 Public Gists

Categories

  • #100DaysOfCode (4)
  • ASP.NET (7)
  • ASP.NET Core (1)
  • ASP.NET MVC (3)
  • CSS (4)
  • General (13)
  • JS (3)
  • LESS (2)
  • Snippets (4)
  • Tools (4)
  • Tutorials (9)

Recent Posts

  • Creating a Knockout.js project on Codepen
  • 100DaysOfCode Day 3 – A State of Mind
  • 100DaysOfCode Day 2 – The Building Blocks
  • 100DaysOfCode Day 1 (Sort of cheated already)
  • Committing to #100DaysOfCode
© 2025 Nubgrammer | Powered by Superbs Personal Blog theme
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
%d

    Privacy Policy