Explore Free C# Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Fri, 24 Feb 2023 21:14:40 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free C# Tutorials – GameDev Academy https://gamedevacademy.org 32 32 How to Build a C# App: Beginner’s C# Programming https://gamedevacademy.org/csharp-programming-tutorial/ Wed, 21 Jul 2021 01:00:05 +0000 https://coding.degree/?p=1185 Read more]]> In this C# programming tutorial, we’re going to show you how to build your first C# app: a calculator.

Not only will these techniques help you practice both the C# programming fundamentals and C# programming logic, but give you crucial experience and a basic understanding in using one of the top 5 programming languages in the entire world!

We’ll be using the in-browser IDE ( relpit.com ) which requires no setup, so if you’re ready, let’s build our app!

About C# Programming

C# is a popular programming language developed by Microsoft. It is an object oriented language based off of the C programming language, so it features many of the same common language infrastructure features. Additionally, it was built on top of Microsoft’s popular Net framework, giving you access to many useful features via the System namespace.

While there are many other popular programming languages out there, C# programming is unique in its balance of efficiency with human readability. It has seen wide use in developing video games, desktop applications, and even mobile applications.

For this tutorial, we already expect you know some C# programming basics such as local variables, primitive types, loops, and so forth. We also assume you’re familiar with using class libraries, in particular the Console class. While we’ll be using Replit, as mentioned above, you are also welcome to follow along with Visual Studio. That being said, we do encourage you to make sure you at least know how to build a simple “Hello World” app first to be assured Visual Studio will run as intended.

Sprint 1 – Pseudocode

Sometimes when you have to perform a programming task that will require more than a couple of steps it can seem a bit overwhelming. It is often helpful to break your task down into simple next steps. These are not all the steps to complete your task but high-level next steps that can at least simulate creating the task result you want.

For example, your task may involve getting data from the user:

  • In our initial iteration, we can note this but choose to provide a “hard-coded” value to simply get our logic working.
  • In the next iteration, we can return to implement logic to get actual user input. At this point, we can enter a value as if we’re the user. Since we know what our app is expecting we enter the value correctly. For example, when our “Calculator App” expects a number we enter a number; when it expects a math operator we enter “+”.
  • In the next iteration, we can choose to handle the situation where the user does not enter the correct information. We can choose how to validate the input and what our program flow should do if the information entered is invalid.
  • In the next iteration, we can choose to expand our error tracking to unexpected errors, called “Exceptions” in C# programming, and introduce logic to both “catch” the error as well as logic on what our app should do when an exception occurs.

As you can see, even with this simple example and a few simple observations, programming can get overwhelming quickly if you try to code all possible features, optimize your code, and protect your app all in the first pass.

Let’s try this approach with our simple C# programming calculator app.

using System;

class MainClass {
  public static void Main (string[] args) {

    // Display App Name as "Simple C# Calculator"

    // Get first number (in 10)

    // Get math operator (in +)

    // Get second number (in 2)

    // Perform calculation to get the result (out 12)

    // Determine if user wants to do more calculations (conditional check)
      // true (if true; most steps repeated) 
        // set first value to last result
        // get next math operator
        // get second number
        // perform calculation to get new result
        // Determine if user wants to do more calculations
      // false (if false)
        // exit Calculator app loop
        // Display result to user (out "Total: 12")
  }
}

Notice that in just this first pass of pseudocode we can see the opportunity to use several key C# programming fundamentals:

  • Variables to hold data being tracked and changed
  • Decision Control based on boolean conditions
  • Loops to repeat code logic
  • Methods to consolidate code for repeating tasks
  • Classes and Objects to encapsulate state and related actions

I know this is a lot but let’s start slow in the next iteration by gradually replacing some pseudocode with actual code. You’ll also notice the need to add additional comments (TODO items) as well as additional pseudocode as we make progress towards our finished C# programming Calculator App.

Banner for C Sharp Calculator

Sprint 2 – Basic Working Code

As we begin to replace pseudocode with actual C# programming code, run your program often to make sure no C# compiler errors are being introduced. This is known as “doing things right”.

As we get blocks of code completed we can expand our testing to include logic, making sure our functionality is correct. This is known as “doing the right things”.

using System;

class MainClass {
  public static void Main (string[] args) {

    Console.Clear();
    // Display App Name as "Simple C# Calculator"
    Console.WriteLine("Simple C# Calculator");

    // Get first number (in 10)
    double firstNum = 10;

    // Get math operator (in +)
    string mathOp = "+";

    // Get second number (in 2)
    double secondNum = 2;


    // Perform calculation to get result (out 12)
    double result = firstNum + secondNum;
    
 
  // Determine if user wants to do more calculations (conditional check; assume FALSE)
  // true (if true; most steps repeated) 
    // set first value to last result
    // get next math operator
    // get second number
    // perform calculation to get new result
    // Determine if user wants to do more calculations
  // false (if false)
    // exit Calculator app loop
    // Display result to user (out "Total: 12")
    Console.WriteLine("Answer: {0} {1} {2} = {3}", firstNum, mathOp, secondNum, result);
    Console.WriteLine("Answer: "+firstNum+" "+mathOp+" "+secondNum+" = "+result);
  }
}

The two Console.WriteLine() options produce the same result. The first method is based on substitution and will obey any spaces or other text inside the double-quotes. The numbers in the substitution syntax {0} correspond to the variable order in the comma-separated list that follows the WriteLine() string. In the second, simple concatenation example, you need to add any spaces you want as double-quotes ” “ with space in-between. Moving forward with this example we’ll use the substitution syntax.

Simple C# Calculator
Answer: 10 + 2 = 12
Answer: 10 + 2 = 12

Sprint 3 – Code While Loop

We can see from the pseudocode, that we need to repeat what we present to the user if the user wants to continue. This lends itself to putting our repeating code inside a Loop with a conditional check that allows us to exit the loop when the user is finished.

This leaves us with two important design decisions:

  • What do we want to do on each iteration? This code will go inside the loop.
  • How do we want the user to indicate they are finished? This must feed into our loop condition.

There are many ways to implement this logic. For example, if the user leaves the “Math Operator” empty we can exit:

  • Let’s print this instruction for the user.
  • Let’s code a while loop to test this option.
using System;

class MainClass {
  public static void Main (string[] args) {
    // Clear the Console before we start displaying calculations
    Console.Clear();
    // Display App Name as "Simple C# Calculator"
    Console.WriteLine("Simple C# Calculator");
    Console.WriteLine("Math Operators: [ + | - | * | / ] leave empty to exit");

    // Declare variables we need for Calculator
    double firstNum, secondNum, result;
    string mathOp = "+";

    // Get first number before loop (in 10)
    firstNum = 10;

    // TODO: remove logic to exit test loop
    int testCounter = 1; 

    /* Determine if user wants to do more calculations based on whether or not the math operators question is left blank (String.Empty in C# programming) */
    // true   - repeat most steps
    // false  - exit Calculator app loop
    while (mathOp != String.Empty) {

      // TODO: remove logic to exit test loop
      if (testCounter < 5) {
        Console.WriteLine("Iteration: {0}", testCounter);
        testCounter++;
      } else {
        mathOp = String.Empty;
        continue;
      }

      // Get math operator (in +)
      mathOp = "+";
      // Get second number (in 2)
      secondNum = testCounter;

      // Perform calculation to get result
      result = firstNum + secondNum;

      // Display result to the user
      Console.WriteLine("Answer: {0} {1} {2} = {3}",firstNum, mathOp, secondNum, result);
      
      // set the first number to be the last result before the loop begins again
      firstNum = result;

    }
  }
}

For test purposes, we have introduced a temporary testCounter which we then use inside the loop to display the current iteration, increment its value, use to simulate more dynamic input from the user and finally set to our while loop exit condition after four test iterations. This simulates the user adding together five numbers before leaving mathOp empty to simulate being done with calculations. The simulation now looks like this inside our Console:

Simple C# programming Calculator
Math Operators: [ + | - | * | / ] leave empty to exit
Iteration: 1
Answer: 10 + 2 = 12
Iteration: 2
Answer: 12 + 3 = 15
Iteration: 3
Answer: 15 + 4 = 19
Iteration: 4
Answer: 19 + 5 = 24

Person working at a calculator in front of a laptop

Sprint 4 – User Input – Numbers

With a basic working data structure of our C# programming Calculator App in place, it’s time to make it real by adding user input. In this next step, we will accept user input and incorporate it into our functionality with no validation or error handling. Our goal is to simply accept user input in place of our current “hard-coded” values for numbers. We will leave the mathOp “hard-coded” to + for this iteration.

The key C# programming Console command we will work with is Console.ReadLine(). To this point in the tutorial, we have focused on printing information to the Console. In this Sprint, we do the opposite by retrieving data the user types into the Console in response to our app’s prompts for information; namely firstNum and secondNum (we will handle mathOp input and processing in the next Sprint).

While Console.ReadLine() will give us access to what the user types in the Conole, it’s important to note that all its input is returned as a String data type (even when we ask for a number and our app can only calculate numbers). For this reason, our app will need to first convert the input strings to Numbers before attempting any calculations. One way to do this is using C# programming’s static Convert class to access its Convert.ToDouble() method which takes the String input from the Console and converts it to a double data-type before storing its, now Number data-type, value in our firstNum variable. We’ll repeat this for the secondNum variable. After firstNum is provided by the user initially, its value is automatically updated by our code to be the previous result.

using System;

class MainClass {
  public static void Main (string[] args) {

    Console.Clear();

    Console.WriteLine("Simple C# Calculator");
    Console.WriteLine("Math Operators: [ + | - | * | / ] leave empty to exit");

    // Declare variables we need for Calculator
    double firstNum, secondNum, result;
    string mathOp;

    // Get first number before loop
    Console.Write("Enter first number: ");
    firstNum = Convert.ToDouble(Console.ReadLine());

    do 
    {
      // Get math operator (in +)
      mathOp = "+";

      Console.Write("{0} + __ : ", firstNum);

      try {
        secondNum = Convert.ToDouble(Console.ReadLine());
      } catch {
        mathOp = String.Empty;
        continue;
      }

      // Perform calculation to get result
      result = firstNum + secondNum;

      // Display result to the user
      Console.WriteLine("{0} {1} {2} = {3}",firstNum, mathOp, secondNum, result);
      
      // Assign result to firstNum before looping again
      firstNum = result;
    } while (mathOp != String.Empty);

    Console.WriteLine("Answer: {0}", result);

  }
}

Notice that we use Console.Write() to prompt the user for a number instead of Console.WriteLine() we’ve been using so far. The key difference is that WriteLine() automatically takes the user to a new line in the Console whereas Write() waits for user input on the same line.

Notice that we use a Try-Catch Block to handle the C# programming exception that will be thrown if the user enters a non-numeric character or leaves it blank. In this scenario, we assume that entering a non-numeric value indicates the calculations have finished so we set the Loop condition exit criteria to true and use the keyword continue to take the code straight to the Loop Condition; which is now false. The loop ends and the final line of the app is printed providing the final answer.

Sprint 5 – User Input – Operator

We can add together as many numbers as we want. The next challenge is to give the user the option to do more than just add numbers.

We will use the same Console.ReadLine() as we did for the firstNum and secondNum in the last section to get the user input. As we know, ReadLine() returns a String. The difference is that for mathOp, we want a String so no conversion is necessary.

What we do need to do is to determine what mathOp symbol was provided. This tells us if we should add, multiple, subtract or divide the firstNum and secondNum.

While we can do this with an IF statement, it’s actually a great use-case for C# programming’s SWITCH Statement which is great when evaluating a selection of known values associated with a single variable.

We’ll use switch to check for +, -, *, / and make the appropriate calculation. If not one of these symbols then we again set the loop exit condition to be false and use the keyword continue to take the code straight to the Loop Condition; which is now false. The loop ends and the final line of the app is printed providing the final answer.

using System;

class MainClass {
  public static void Main (string[] args) {

    Console.Clear();

    Console.WriteLine("Simple C# Calculator");
    Console.WriteLine("Math Operators: [ + | - | * | / ] leave empty to exit");

    // Declare variables we need for Calculator
    double firstNum, secondNum, result = 0;
    string mathOp = "+";
    string[] ValidMathOperators = {"+","-","*","/"};

    // Get first number before loop
    Console.Write("Enter first number: ");
    firstNum = Convert.ToDouble(Console.ReadLine());

    while (mathOp != String.Empty) {
      try {
      
        // Get math operator (input from user)
        Console.Write("Enter math operator: ");
        mathOp = Console.ReadLine();

        // check if math operator entered by user is valid; if not exit loop
        if (!Array.Exists(ValidMathOperators, e => e == mathOp)) {
          Console.WriteLine("Invalid Math Operator");
          mathOp = String.Empty;
          continue;
        }

        // Write the first part of the equation
        Console.Write("{0} {1} ", firstNum, mathOp);

        // Get second number (input from user)
        secondNum = Convert.ToDouble(Console.ReadLine());
      } catch {
        Console.WriteLine("Does Not Compute!");
        mathOp = String.Empty;
        continue;
      }

      // determine which math operator the user entered
      switch (mathOp) {
        case "+":
          result = firstNum + secondNum;
          Console.WriteLine("Add: {0}", result);
          break;
        case "-":
          result = firstNum - secondNum;
          Console.WriteLine("Subtract: {0}", result);
          break;
        case "*":
          result = firstNum * secondNum;
          Console.WriteLine("Multiply: {0}", result);
          break;
        case "/":
          result = firstNum / secondNum;
          Console.WriteLine("Divide: {0}", result);
          break;
        default:
          // error with math operator so exit calculation loop
          mathOp = String.Empty;
          continue;
      }

      // Display result to the user
      Console.WriteLine(" = {0}", result);
      
      // Assign result to firstNum before looping again
      firstNum = result;
    }

    Console.WriteLine("Answer: {0}", result);

  }
}

We now have a working, interactive C# programming Calculator. Here is an example, displayed step by step, in the Console:

Simple C# Calculator
Math Operators: [ + | - | * | / ] leave empty to exit
Enter first number: 7
Enter math operator: +
7 + 7
 = 14
Enter math operator: *
14 * 2
 = 28
Enter math operator: -
28 - 8
 = 20
Enter math operator: /
20 / 5
 = 4
Enter math operator: 
Invalid Math Operator
Answer: 4

Banner for C Sharp Calculator

Sprint 6 – Classes and Methods

We now have a working, interactive C# programming Console Calculator but we have a lot of code in the Main method. We can improve our calculator, by making its implementation cleaner and more reusable by moving some of the logic into Classes and Methods.

C# is an Object-Oriented programming language. Object-Oriented Programming (OOP) is a major subject in itself so this will just be a high-level overview of what you need to know to begin using Classes and Methods in C# programming. There are four pillars of OOP and we’ll touch on the first two in this Sprint. The four pillars are:

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

The idea behind OOP is to model “real-world” objects using Classes! In our case, we will use a C# programming class as a “blueprint” for a “real-world” calculator. By doing this we “abstract” the internal workings of our calculator, let’s say the “logic board”, from the outside display and user interaction. The logic board’s specific data (Properties) and functionality (Methods) are now “encapsulated” inside a C# programming class which hides its inner workings (how it performs calculations) from the outside world. What goes into the Calculator class depends on how we want to model the calculator. If we say the inside of the calculator handles memory, calculation and validation then we could use the Main method to hold the calculator’s UI and keyboard interactions with the user.

Following this idea let’s create a Calculator class and move the following functionality into it:

  • Memory – variables to store numbers and math operator
  • Conversion – converting input into useable numbers
  • Validation – ensuring the math operator entered is a valid math symbol
  • Calculation – based on the first and second number together with math operator
  • Finished – determines when the user is finished calculating numbers

Keep in the Main method:

  • Display Welcome and Calculator information to the user
  • Start Calculator by creating a Calculator Object
  • WriteLine() – displaying results to the user
  • ReadLine() – getting information from the user
  • App Loop – considered to be the user interacting with the calculator
  • Exit – observes the finished indicator from the Calculator class and stops the app from running when ContinueCalculating is set to false
using System;

class MainClass {
  public static void Main (string[] args) {
    // Clear Console and Welcome User
    Console.Clear();
    Console.WriteLine("Simple C# Calculator");
    Console.WriteLine("Math Operators: [ + | - | * | / ]");

    Calculator calc = new Calculator();

    // Get the first number before loop starts
    Console.Write("Enter first number: ");
    calc.SetNumber(Console.ReadLine());

    while (calc.ContinueCalculating) {
      
      // Get math operator (input from user)
      Console.Write("[ + | - | * | /  ] ");
      calc.MathOp = Console.ReadLine();

      // Get second number (input from user)
      Console.Write("{0} {1} ", calc.FirstNum, calc.MathOp);
      calc.SetNumber(Console.ReadLine());

      if (calc.ContinueCalculating) {
        // Calculate Result
        calc.Calculate();
        // Display Result to the User
        Console.WriteLine(" = {0}", calc.Result);
      }

    }

    Console.WriteLine("Result: {0}", calc.Result);

  }
}

// --- Calculator Class --- (could be in separate file)
  
class Calculator {
  // Declare private variables
  private string[] validMathOperators = {"+","-","*","/"};
  private string prevMathOp, mathOp;
  private bool firstNumber;

  // Declare Calculator Properties
  // (read value from anywhere; set value only in this class)
  public bool ContinueCalculating {get; private set;}
  public double FirstNum {get; private set;}
  public double SecondNum {get; private set;}
  public double Result {get; private set;}

  public string MathOp {
    get { return mathOp;} 
    set {  
      if (Array.Exists(validMathOperators, el => el == value)) {
        mathOp = value;
      } else {
        mathOp = prevMathOp;
      } 
    }
  }

  // Class Constructor
  public Calculator() {
    // Initialize Properties and Variables when Calculator Object is created
    prevMathOp = validMathOperators[0];
    firstNumber = true;
    ContinueCalculating = true;
  }

  // public Methods
  public void SetNumber (string input) {
    double number;
    try {
      number = Convert.ToDouble(input);
    } catch {
      number = 0;
      ContinueCalculating = false;
    }
    if (firstNumber) {
      FirstNum = number;
      firstNumber = false;
    } else {
      SecondNum = number;
    }
  }

  public void Calculate() {

    // Perform Calculation based on FirstNum, MathOp, SecondNum
    switch (MathOp) {
      case "+":
        Result = FirstNum + SecondNum;
        break;
      case "-":
        Result = FirstNum - SecondNum;
        break;
      case "*":
        Result = FirstNum * SecondNum;
        break;
      case "/":
        Result = FirstNum / SecondNum;
        break;
      default:
        break;
    }

    /* 
    We continue calculating from the previous number...
    We accomplish this by assigning the current Result to the FirstNum property once the current calculation is complete. 
    */
    FirstNum = Result;
    /* 
    We want the math operator to default to its previous value if the user leaves it blank...
    We accomplish this by using a previous math operator variable and assigning the current math operator value once the current calculation is complete. 
    */
    prevMathOp = MathOp;

  }
}

We now have a working, interactive C# programming Console Calculator. Here is an example, displayed step by step, in the Console:

Simple C# Calculator
Math Operators: [ + | - | * | / ]
Enter first number: 5
[ + | - | * | /  ] 
5 + 6
 = 11
[ + | - | * | /  ] 
11 + 7
 = 18
[ + | - | * | /  ] *
18 * 4
 = 72
[ + | - | * | /  ] / 
72 / 9
 = 8
[ + | - | * | /  ] 
8 / 
Result: 8

Notice, in the above code, that in our Calculator class Properties we use Property Getters and Setters. This allows you to control access to your class. In this example, we allow anyone outside our class to read and write to the MathOp Property but we perform validation in the Setter before any value is actually assigned in our class. If the validation is true, we assign the value from the user. If the validation is false, we assign the previous math operator value instead.

For our Numbers ( FirstNum and SecondNum ) Properties we only allow those values to be set within the Calculator class. We can do this by making the Property’s Setter private. Now the value is updated by using a class Method which provides us with the opportunity to validate user input, convert input into the number format we need and control what happens when the user enters nothing at all.

Finally, we use a Calculator class property in the Main method app loop to evaluate the exit condition. Inside the Calculator class, we change this exit condition to be an empty value for secondNum and implement it by setting the class Property ContinueCalculating to false. This value is then read by the Main method and directs the code to break out of the app loop. This causes a final message to print to the user and then ends the program.

Sprint 7 – Refactor App using C# Inheritance

In the last section, we abstracted the internal workings of our calculator into its own class thereby cleaning up the Main method of the application considerably. At present, the Main method still contains all the display and user interaction logic which is a lot of code.

Let’s say we want the Main method to simply handle our app’s code execution and not directly hold any logic related to the calculator. In designing this solution we could also consider future development. What does this mean?

At the moment we are developing a calculator in the Console. Perhaps in the future, we may develop a web calculator or a desktop calculator. While this would alter the “exterior”, such as display and user interaction, the “internal” workings of the calculator could remain the same. We can create a new ConsoleCalculator class without changing anything about our existing Calculator class yet have access to all of its functionality. We do this by using another Object-Oriented Programming (OOP) practice, known as “inheritance”. In the code below, notice that only the Main method where the object ( calc ) is created uses this object reference. All the logic that has been refactored out of Main no longer uses the object reference since it is now inside a different class.

using System;

class MainClass {
  public static void Main (string[] args) {

    ConsoleCalculator calc = new ConsoleCalculator();

    calc.On();

    calc.GetFirstNumber();

    while (calc.ContinueCalculating) {
      calc.GetMathOperator();
      calc.GetSecondNumber();
      calc.Calculate();
    }

    calc.Off();

  }
}

/* --- ConsoleCalculator Class --- (could be in separate file)
ConsoleCalculator inherits from its base class Calculator 
using the following syntax:
*/

class ConsoleCalculator : Calculator {

  public void On() {
    // Clear Console and Welcome User
    Console.Clear();
    Console.WriteLine("Simple C# Calculator");
    Console.WriteLine("Math Operators: [ + | - | * | / ]");
  }

  public void Off() {
    Console.WriteLine("Result: {0}", Result);
  }

  public void GetFirstNumber() {
    // Get the first number before loop starts
    Console.Write("Enter first number: ");
    SetNumber(Console.ReadLine());
  }

  public void GetMathOperator() {
    // Get math operator (input from user)
    Console.Write("[ + | - | * | /  ] ");
    MathOp = Console.ReadLine();
  }

  public void GetSecondNumber() {
    // Get second number (input from user)
    Console.Write("{0} {1} ", FirstNum, MathOp);
    SetNumber(Console.ReadLine());
  }

  public void Calculate() {
    if (ContinueCalculating) {
      // Calculate Result
      base.Calculate();
      // Display Result to the User
      Console.WriteLine(" = {0}", Result);
    }
  }
}

// --- Calculator Class --- (could be in separate file)
// Existing Code - no changes required

In the code above, we refactor the Main method to move all of the Console Calculator’s display and user interaction logic into the ConsoleCalculator class:

  • Display Welcome and Calculator information to the user
  • WriteLine() – displaying results to the user
  • ReadLine() – getting information from the user

This now represents the “exterior” of our calculator. Since we still need access to our “internal” logic we have ConsoleCalculator “inherit” from Calculator using the following :  syntax:

class ConsoleCalculator : Calculator {
  // ConsoleCalculator code
}

The new ConsoleCalculator class is known as the “derived” class and the Calculator class is known as the “base” class. Inheritance allows us to directly access all the Properties ( such as Result, FirstNum, and MathOp ) and Methods ( such as SetNumber() ) of the base class (Calculator). We also have a special case in the method named Calculate() since it appears in both classes. This enables the derived class to implement behaviour specific to the ConsoleCalculator while also executing the functionality contained in the base class. Since the default within the ConsoleCalculator, or any object created from it (calc in the Main method), is to call the ConsoleCalculator‘s method we tell our C# programming to execute the base class method using the base keyword as follows:

public void Calculate() {
  if (ContinueCalculating) {
    // Calculate Result using base class
    base.Calculate();
    // Display Result to the User
    Console.WriteLine(" = {0}", Result);
  }
}

We have now successfully abstracted and encapsulated the internal and external workings of our calculator into their own classes. Also, since we inherited the internal workings from the base Calculator class (created in the previous Sprint) we can reuse this base class code to create other types of calculators, such as web or desktop, in the future. We also have a very clean Main method that handles only our app’s high-level execution:

  • Start Calculator by creating a Calculator Object
  • App Loop – considered to be the user interacting with the calculator
  • Exit – observes the finished indicator from the Calculator class and stops the app from running when ContinueCalculating is set to false

Conclusion

Congratulations! You have just coded a working, object-oriented C# programming calculator app from scratch!!!

Over this C# programming tutorial, we’ve covered a lot. We’ve learned how to deal with user input, utilize computer calculations, and address topics like inheritance. Most importantly here, though, we’ve learned how to take a base concept and slowly build upon it until we were able to create a clean-looking code base for our app to run on.

Of course, this is just the start. C# is a general-purpose language, and it can do a lot – even beyond simple Console applications. Software, video games, and so much more are available to you, which is why C# is one of the most popular programming languages. Even not considering projects themselves, there are many functional programming techniques to explore with C# not covered here, such as: making user defined types, setting up static methods, using multiple interfaces, and so forth.

So get out there and start making your own apps!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Free Coding eBook – Coding for Beginners https://gamedevacademy.org/free-ebook-coding-for-beginners/ Tue, 09 Feb 2021 10:03:31 +0000 https://coding.degree/?p=417 Read more]]> Learn how to code in a beginner-friendly way with our free, in-depth coding eBook: Coding for Beginners

Created by Allan Carlos Claudino Villa, this eBook will help you learn your first amount of coding by exploring the popular C# language. You’ll master a variety of essential coding fundamentals needed for all languages, and also explore how these elements will help you start developing your own pieces of software. Not only will these foundations prove crucial as you expand and develop your own projects, even if you switch to another coding language, but they will prepare you to create both software, games, and more with knowledge that can be adapted to multiple fields.

Mastering in-demand skills to enhance your career or hobbies are at your fingertips, no matter what your ultimate coding goals are!

Download the eBook here

]]>
Cross Platform Apps with Xamarin for Beginners https://gamedevacademy.org/cross-platform-apps-with-xamarin-for-beginners/ Tue, 21 Feb 2017 23:29:52 +0000 https://html5hive.org/?p=1737 Read more]]> Are you comfortable with C#? Then you are ready to learn how to build both iOS and android applications using Xamarin. With the increasing numbers of smartphone users,  mobile devices have become the first step for many users when they are looking for product reviews, shopping or playing games. You need to be able to develop in a single code base using one language and then use it across multiple platforms.

Using Xamarin for you mobile app development just makes sense. You only need one language, C#. Because you are using a single code base it is a faster time to market for your projects and because you are using a single language, fewer bugs to track down and fix.

Access this course on Zenva Academy

 

]]>
Free Ebook – C# Programming for Human Beings https://gamedevacademy.org/free-ebook-c-sharp-programming-for-human-beings/ Mon, 07 Nov 2016 08:41:02 +0000 https://html5hive.org/?p=1707 Read more]]> We are very excited to announce our new ebook C# Programming for Human Beings by Allan Carlos Claudino Villa, which covers the very basics of computer programming using Visual Studio.

This book assumes no prior programming experience and it’s suitable for complete beginners.

C# is one the most popular programming languages, used in different applications such as:

  • Server-side web development using the .NET framework
  • Cross-platform desktop application development
  • Mobile application development using Xamarin
  • Game and virtual reality development using Unity3D

This book is provided at no cost in PDF format.
Download the ebook.

What cool projects are you interested in building? Let us know in the comments!

 

 

]]>
.Net for Beginners https://gamedevacademy.org/net-for-beginners/ Mon, 24 Oct 2016 00:02:10 +0000 https://html5hive.org/?p=1622 Read more]]> .NET is a programming framework created by Microsoft that is used for developing Windows and web-based applications. Developers can use it to create applications more easily and it is one of the most widely used enterprise environments in the world. If you are looking to learn enterprise level development then this is the course for you.

Just because this course is for beginners doesn’t mean it’s not comprehensive! This course will show you how to build a full Windows application including database back end. You’ll tour a web-based application and learn how to integrate the many useful .net libraries. If you are ready, your enterprise development career starts here!

Access this course on Zenva Academy

]]>
C# Basic – Lesson 5: Methods, Exception Treatments, Classes and Object-Oriented https://gamedevacademy.org/c-basic-lesson-5-methods-exception-treatments-classes-and-object-oriented/ Thu, 01 Sep 2016 23:29:51 +0000 https://html5hive.org/?p=1582 Read more]]> Hi and welcome to the Lesson 5 – Methods, Exception Treatments, Classes and Object-Oriented on our tutorial series Learning C# with Zenva.

Tutorial Source Code

All of the source code for this tutorial can be downloaded here.

A method is a group of statements that together not only perform a task but also help to organise our code. Every C# program has at least one class with a method named Main. A class is where you will organise your methods and variables. In this lesson, we will discuss more about it. When we first create a new project, the project comes with a class called Program and a method called Main(), have you noticed it?  In this lesson, we are going to learn how to define methods and use them, handle exceptions and treat them using the command “try”.

Before we start, remember back in Lesson 2, I said about access modifiers. They suit for both variables and methods. Let’s understand them. The three most used are:

Public: visible for all classes.

Private: visible to the class they belong.

Protected: visible to the class they belong and any subclass.

When we do not specify our modifier, by default it is private.

Defining Methods

A Method has the following syntax:

<access specifier> <Return type> <Method name> (Parameter List)
{
   Method body
}

Each method has his own signature, that is, name and parameters. I can have two methods with the same name but different parameters. This includes a number of parameters and type.

Let’s start a new project, choose console application and name it MethodsAndException. Write or copy and paste the code below.

First example: Adding two numbers.

using System;

namespace MethodsAndException
{
    public class Program
    {
        //method is static because I am calling it from the static method Main
        public static void SumTwoNumbers(int number1, int number2)
        {
            Console.WriteLine(number1 + " + " + number2 + " = " + (number1 + number2));
        }

       
        public static void Main(string[] args)
        {
            int n1, n2;

            Console.WriteLine("Give me two numbers and I give you their sum!");
            Console.Write("What is your first number: ");
            n1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("What is your second number: ");
            n2 = Convert.ToInt32(Console.ReadLine());

            //calling the method.
            //SumTwoNumbers(n1, n2);

         
            Console.Read();
        }
    }
}

Understanding new code:

In this example, I made my class and methods public. The method SumTwoNumbers receives as parameters two integers, number1, and number2. It has on its return type, void, that is, the method does not return a value. This method simply sums the two numbers and shows on screen. Note that I am doing the operation in the message itself. I could create a variable to receive the sum and then write this variable, “result”  for example, in the message. To call a method, we write its name and provide the parameters needed.

Second example: Who is greater?

using System;

namespace MethodsAndException
{
    public class Program
    {
        ////method is static because I am calling it from the static method Main
        //public static void SumTwoNumbers(int number1, int number2)
        //{
        //    Console.WriteLine(number1 + " + " + number2 + " = " + (number1 + number2));
        //}


        //method return is a bool value (true or false)
        public static bool WhoIsGreater(int A, int B)
        {
            if (A > B)
                return true;
            else
                return false;
        }

        public static void Main(string[] args)
        {
            //int n1, n2;

            //Console.WriteLine("Give me two numbers and I give you their sum!");
            //Console.Write("What is your first number: ");
            //n1 = Convert.ToInt32(Console.ReadLine());
            //Console.Write("What is your second number: ");
            //n2 = Convert.ToInt32(Console.ReadLine());

            //calling the method.
            //SumTwoNumbers(n1, n2);

            if (WhoIsGreater(10, 5)) //if is true than A > B. Here you can change values for testing.
            {
                Console.WriteLine("A is greater than B");
            }
            else
            {
                Console.WriteLine("A is greater than B");
            }

            Console.Read();
        }
    }
}

The method WhoIsGreater also receives two parameters (integer),  A and B. This method verify if A is greater than B and return true if condition applies or false if B is greater than A.  In this case, we set return type as bool, that is, returns a Boolean value(true or false).

Running our applications:

5.1

5.2

Exception Treatments

What if, instead of a number, the user types a word or some character that is not a number? An exception would occur:

5.3

What is happening is: we are trying to convert a char to number, which is kind impossible. To handle this exception and many others, we use the command “try”. Let’s understand.

try
{

}
catch (Exception)
{
   throw;
}

We try to do something. If an exception occurs, it goes directly to “catch” and we can show a message to the user. So, let’s put our code where we try to convert what the user type to int, inside the try-catch.

try
{
    Console.WriteLine("Give me two numbers and I give you their sum!");
    Console.Write("What is your first number: "); 
    n1 = Convert.ToInt32(Console.ReadLine());
    Console.Write("What is your second number: ");
    n2 = Convert.ToInt32(Console.ReadLine());

    //calling the method.
     SumTwoNumbers(n1, n2);
}
catch (Exception)
{
    Console.WriteLine("This is not a number!");
}

Now, our exception is treated!

5.4

Classes and Object-Oriented

A class consists of a group of variables, methods, and events that together enables you to create a construct by grouping these items. A class is simply a representation of an object type. It is like a structure that describes an object. By the way, an object is basically a block of memory that has been allocated and configured in accordance with the model. A program can create multiple objects of the same class. The object orientation is a bridge between the real world and the virtual, from this, it is possible to transcribe the way we see real world elements to our source code, in order to enable us to build complex systems based on objects.

Before we follow the example, let’s start a new project, choose console application and name it ClassesAndObjects, write or copy and paste the codes below.

So, let’s think about a person. A person has some attributes. In our case, we will create the followings: first name, last name, and age. With what you learnt until now, our code would look like this:

namespace ClassesAndObjects
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string firstname, lastName;
            int age;
        }
    }
}

But what if we need to add one more person? New variables, firstName2, lastName2, age2? What about 5, 10, 100 records? Let’s create a class!!

namespace ClassesAndObjects
{
    public class Person
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public int age { get; set; }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
           
        }
    }
}

Note that, when we are programming object-oriented, we do not use fields as our variables. We now use Property.

A Property is a member that provides flexible ways to read, write, or compute values of fields. A get property accessor is used to return the property value, and a set accessor is used to assign a new value.

Tip: To write a property, try writing prop and press ‘tab’ twice.

Ok, but now, how to have access to these properties of this class? We create an object! To create an object, we need to instantiate the class and by doing that, we now have access to the class properties and methods. By pressing “dot” on my object p type Person(class), it shows all methods and properties accessible of this class.

image5

Let’s set some values and show these values in our application.

using System;

namespace ClassesAndObjects
{
    public class Person
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public int age { get; set; }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            //declaring a variable type Person (class)
            Person p = new Person();
            p.firstName = "Alex";
            p.lastName = "Wilson";
            p.age = 37;

            Console.WriteLine("Hi, my name is "+ p.firstName +" "+ p.lastName + ". I am "+ p.age +" years old.");
            Console.Read();
        }
    }
}

Running our application:

5.5

Now if you want a new Person, it is easy. Just create new objects of Person with different names, for instance, p2, p3, p4… as you want.

Note that our message is full of ” “ and +. We certainly can get confused when we have to show a lot of information. So, there are two ways to show the same message:

Using format:  We can use {n} to determine the quantity of our variables.

Console.WriteLine("Hi, my name is {0} {1} {2}  years old.", p.firstName, p.lastName, p.age);

Now with C# 6.0 we can write like this: We put a $ before the string, so ‘{ }’ are not recognised as part of the string and yes a property.

Console.WriteLine($"Hi, my name is {p.firstName} {p.lastName} {p.age}");

As I said, classes also can have methods. So let’s create a method to check  age of majority.

public class Person
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public int age { get; set; }

        public string AgeOfMajority(int age)
        {
            if (age >= 18)
                return "You are of legal age!";
            else
                return "You are not of legal age!";
        }
    }

Now let’s receive the user age and check if the user is of legal age by calling the method AgeOfMajority();

Person p2 = new Person();
Console.Write("How old are you? ");
int myAge = Convert.ToInt32(Console.ReadLine());

Console.WriteLine(p2.AgeOfMajority(myAge));

Running our program:

5.6

This is our last tutorial about learning Basic C# . I hope you have enjoyed.

Thank you!

]]>
C# Basic – Lesson 4: Arrays and Lists https://gamedevacademy.org/c-sharp-lesson-4-arrays-and-lists/ Thu, 01 Sep 2016 23:29:46 +0000 https://html5hive.org/?p=1580 Read more]]> Hi and welcome to the Lesson 4 – Arrays and Lists on our tutorial series Learning C# with Zenva.

Tutorial Source Code

All of the source code for this tutorial can be downloaded here.

In this lesson, we will see what is an array and what is a list; the difference between them; how to declare and use them together with the for statement we learnt in the last lesson.

ARRAYS

An Array is a data collection of the same type. A feature of the arrays is that they are static, that is, the programmer cannot increase the amount of positions in runtime. So if we declare an array of int with 10 positions, these positions will remain until the end of the program for this array.

Arrays have the following syntax:

Data type[] arrayName;

Data Type: specify the type of elements in the array.

[ ] : specify the size of the array.

arrayName: specify the name of the array.

When we declare an array, it does not mean it is initialized in the memory because by now, we cannot assign values to it.

Arrays, lists and objects, need to be initialized so we can assign them values. To initialized these structs, we use the word new. For example:

int[] ages = new int[5]

Remember: An array start its index in position 0. It means, an array with 3 positions will have as index: [0][1][2]. We can have access to the array content using the index. There are several ways to assign value to an array. Let’s see them:

Using the index number:

string[] names = new string[5]
names[0] = "Zenva";

When we declare the array:

int[] numbers = new int[5] {10, 20, 30, 40, 50}

double[] salary = {150.0, 2400.0, 175.39, 788.68}

//In this case, the array salary has 4 positions.

We can also omit the size:

int[] score = new int[] {10, 20, 30, 40, 50}

//In this case, the array length is 5.

Note: ‘//’ is used to write comments in the code.

We can assign a value from an array, using the index, to a variable:

int[] numbers = new int[5] {10, 20, 30, 40, 50}

int n1 = numbers[3]; //Now n1 = 30.

Time to write some code! Let’s start a new Project and name it ArrayAndList. Write or copy and paste the code below.

Array example:

using System;

namespace ArrayAndList
{
    class Program
    {
        static void Main(string[] args)
        {
            //String array with 3 elements
            string[] names = new string[3];
            names[0] = "Davis";
            names[1] = "Matt";
            names[2] = "Bob";

            for(int i = 0; i < names.Length; i++)
            {
                Console.WriteLine("Position number "+ i +": "+ names[i]);
            }

            Console.Read();
        }
    }
}

In this example, we declared an array of type string with 3 positions and we wrote one name on each position. Then we showed that content of the array using a flow control we learnt last lesson, “for”, to go through each position of the array. Reading the command: “from i = 0 to names.length (in this case length = 3), do something, then, increment the variable i.”

Running our application:

image1

We can also use the structure for to fill our array with numbers, for instance:

int[] numbers = new int[3];

for (int i = 0; i < numbers.Length; i++)
{
   numbers[i] = i + 5;
   Console.WriteLine("Our array numbers has in position [" + i + "] the value: " + numbers[i]);
}

LISTS

A List(T) has the same characteristics of an array. However, a List(T) can be increased dynamically. In a List(T), we do not establish its length. As we need more values to be put into a list, we simply write the method ‘Add’ and we add a new value.

A List(T) has the following syntax:

List<data type> listName;

Also to initialize the list we use the word ‘new’.

listName = new List<data type>();

Both arrays and lists are very easy to work. Also, they are simple and powerful.

List example:

using System;
using System.Collections.Generic;

namespace ArrayAndList
{
    class Program
    {
        static void Main(string[] args)
        {
            #region

            //Declaring a list "int".
            List<int> list = new List<int>();

            //Populating the list with 10 elements
            for(int i = 0; i <= 10; i++)
            {
                list.Add(i*9);
            }

            int x = 0;

            //foreach element in the list do:
            foreach(int element in list)
            {
                Console.WriteLine("9 * " + x + " = " + element);
                x++;
            }

            Console.Read();
        }
    }
}

In this example, we did the multiplication table 9. It was declared a list of type int and we add some numbers using the repeat loop for. Then we showed its content by using the foreach. Also, we need to declare on the top of the code, the using System.Collections.Generic to be able to use List(T).

Running our application:

image2

We can also add items provided by an array in a list. With an array to check its size, we use the method length. With a List(T), we use the method Count.

List<double> orders = new List<double>(new double[] { 19.99, 6.48, 25.0 });

            for (int i = 0; i < orders.Count ; i++)
            {
                Console.WriteLine("Order number " + i + " : $ " + orders[i]);
            }

Count: We can assign the size of a list to a variable by writing:

int ordersQuantity = orders.Count;

Console.WriteLine(ordersQuantity);

//Result: 3

Clear: To remove all the elements from a list we use the function Clear().

orders.Clear();

Console.WriteLine(orders.Count);

//Result: 0

IndexOf: Give us the element index of a value in the List(T). When the method IndexOf does not find the value, it returns as value -1;

int index = orders.IndexOf(25.0);
Console.WriteLine(index);

//Result: 2

Reverse: Invert the order of the elements in the list.

List<string> cars = new List<string>(new string[] { "Ferrari", "Lamborghini", "Range Rover" });
cars.Reverse();

foreach (var car in cars)
{
    Console.WriteLine(car);
}

//Result:
//Range Rover
//Lamborghini
//Ferrari

Distinct: Remove duplicates elements in the list. This method belongs to System.Linq, so we need to add this using System.Linq in our application.

List<int> oldList = new List<int>(new int[] { 1, 2, 2, 3, 4, 4, 5 });

//Get distinct elements and convert into a list again.
List<int> newList = oldList.Distinct().ToList();

foreach (var item in newList)
{
    Console.WriteLine(item);
}

//Result
//1
//2
//3
//4
//5

This is the end of this tutorial. I hope you have enjoyed and I see you in the next lesson!

Thank you!

]]>
C# Basic – Lesson 3: Flow Control in C# https://gamedevacademy.org/c-sharp-lesson-3-flow-control-in-c/ Thu, 01 Sep 2016 23:29:41 +0000 https://html5hive.org/?p=1578 Read more]]> Hi and welcome to the Lesson 3 – Flow Control in C# on our tutorial series Learning C# with Zenva.

Tutorial Source Code

All of the source code for this tutorial can be downloaded here.

Sometimes, a program needs to repeat a process until some condition is met. We call that loop”.  In this lesson, we will see how to work with some structures as for instance, if statement, switch statements, while, do while, for and foreach. Let’s begin.

IF STATEMENT

The instruction IF has the following syntax:

if(expression)
{
   statement;
}

The “if”  statement determines which way the program will continue. With the “if” statement, the program has to decide if it will execute some code or not.

First example: Let’s write a code using the method “Compare” from the String class we learned in the last lesson.

Considering str1 = “Learning C# with” and str2 = “Zenva.”;

Start a new project, name it FlowControlIfExample and write or copy and paste the code below.

using System;
namespace FlowControlIfExample
{
    class Program
    {
        static void Main(string[] args)
        {
            const string str1 = "Learning C# with ", str2 = "Zenva";

            if(string.Compare(str1, str2) == 0)
            {
                Console.WriteLine("The two strings are equal!");
            }
            else
            {
                Console.WriteLine("The two strings are different");
            }

            Console.Read();
        }
    }
}

Understanding new code:

const string str1 = “Learning C# with”, str2 = “Zenva.”; Here I am declaring two constants, type string and initializing its value. The word const before everything means that this constant will not be modified. The two constants are separable by the comma.

As we observe, the program has an If statement to decide which way to go. In our example, we are comparing two strings if they are equals. If the result is 0 or (true), the program executes the first statement, else (meaning not true or 1) the program executes the second statement.

Running our program we have that the two strings are not equal.

3.1

We can use a ternary operator (?:) too (if-then-else constructs).

int n1 = 5, n2 = 1;
string result =  n1 > n2 ? "N1 is greater" : "N2 is greater";

//result: N1 is greater

Second example: using the methods “Contains” and “Replace”

Considering str1 = “Alan bought a Ferrari”;

using System;
namespace FlowControlIfExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // const string str1 = "Learning C# with ", str2 = "Zenva";

            /* if(string.Compare(str1, str2) == 0)
             {
                 Console.WriteLine("The two strings are equal!");
             }
             else
             {
                 Console.WriteLine("The two strings are different");
             } */

            const string str1 = "Alan bought a Ferrari.";

            //Verifying if the condition is NOT TRUE (!)
            if (!str1.Contains("bought")) 
            {
                Console.WriteLine("The str1 does not contain the word bought.");
            }
            else if (str1.Contains("Ferrari.")) //if the condition is TRUE
            {
                Console.WriteLine("What word do you want instead of Ferrari? ");
                string str2 = Console.ReadLine(); //gets the string from the user

                string str3 = str1.Replace("Ferrari", str2); //declaring str3 to receive the str1 content replaced

                Console.WriteLine(str3); //showing the new sentence.            
            }
            Console.Read();
        }
    }
}

To comment the code we can use “//” in front of the line or /* */ for a block. When we have commented code, our application will not execute that line or block.

So in this code, we verify, if the first condition is NOT TRUE, (remember the operator “!”), we show a message that the word we chose to check in contains method does not exist in the specified sentence. If the word exists, then we go and check if exists the word “Ferrari”. If exists we ask for the user what word he wants instead of Ferrari. We read what the user type and store in the variable str2 that we just created.

Using the method replace, we pass the str1 + the new word using the replace method to the str3 and show it in the console application.

if else statement vr

SWITCH STATEMENT

This statement is another way to simulate the use of several if statements. When the condition is met, we use the word “break” to interrupt the program of keep looking for other condition inside this statement. All early types (int, string, double, etc.) can be used with the instruction “switch.”

The instruction SWITCH has the following syntax:

switch(expression)
{
   case constant-expression:
                     statement(s);
                     break;
   default: default expression;
}

Example: The program asks the user to type a value between 1 and 7 which determines the day of the week.

For this example, let’s create another project and give it a name FlowControlExamples.

using System;

namespace FlowControlExamples
{
    class Program
    {
        static void Main(string[] args)
        { 
            Console.Write("Type a number 1 - 7 to see the day of the week corresponding to this number: ");
                       
            //Converting string to Int32.
            int numberDayOfWeek = Convert.ToInt32(Console.ReadLine());

            switch (numberDayOfWeek) //Checking the number the user typed.
            {
                case 1:
                    Console.WriteLine("The day number "+ numberDayOfWeek +" is Sunday!");
                    break;
                case 2:
                    Console.WriteLine("The day number " + numberDayOfWeek + " is Monday!");
                    break;
                case 3:
                    Console.WriteLine("The day number " + numberDayOfWeek + " is Tuesday!");
                    break;
                case 4:
                    Console.WriteLine("The day number " + numberDayOfWeek + " is Wednesday!");
                    break;
                case 5:
                    Console.WriteLine("The day number " + numberDayOfWeek + " is Thursday!");
                    break;
                case 6:
                    Console.WriteLine("The day number " + numberDayOfWeek + " is Friday!");
                    break;
                case 7:
                    Console.WriteLine("The day number " + numberDayOfWeek + " is Saturday!");
                    break;

                default: Console.WriteLine("This number is invalid.");
                    break;
            }

            Console.Read();
        }
    }
}

Understanding new code:

As everything the user writes is a string, a number written in the console application is a string that needs to be converted to int type when the user writes numbers.

The difference between int16, int32, and int64 is their length.

Int16 — (-32,768 to +32,767)

Int32 — (-2,147,483,648 to +2,147,483,647)

Int64 — (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)

Running our application:

switch statement C#

Imagine that the user is a nice guy and writes only numbers. But, what if the user had written text instead of numbers? An exception will be triggered because we are trying to convert letters to an int type. In this case, we had a FormatException.

3.4

Handling exceptions  will be discussed in Lesson 06.

While and Do/While statements

While: used to repeat a block of code until a condition is true. The condition to execute the loop must be a boolean value.

The instruction WHILE has the following syntax:

While (expression)
{
statements;
}

Do/While: works as same as the while, but using this statement we have our code executed at least once.

using System;

namespace FlowControlExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            #region
           
            int x = 0; //creating a variable int starting with 0 as value.

            //Here the program shows us 0 as result
            Console.WriteLine("The value of 'x' is: "+ x);

            //the program shows x incrementing one by one until 10.
            //++x means x = x + 1;
            while (x < 10)
            {
                Console.WriteLine("The value of 'x' is: " + ++x);
            }

            Console.Read();
        }
    }
}

As you can see, there is a different word in the code: #region. My last code is all commented inside this “region”.

image5

Running our application:

3.5

FOR / FOREACH

Also used for loops, but the difference is that here we already know how many times the condition will repeat. We declare a counter variable, which is automatically increased or decreased in value during each repetition of the loop.

The instruction FOR has the following syntax:

for (initialisation, expression, variable update)
{
statements;
}

foreach (element in collection) 
{ 
statements; 
}

With the for statement we specify the loop bounds (minimum or maximum) while with the foreach statement we do not need to specify a boundary.

We will write some code using the command for and foreach in the next lesson!

This is the end of this tutorial. I hope you have enjoyed and I see you in the next lesson!

Thank you!

]]>
C# Basic – Lesson 2: Operators, Variables and Data Types. https://gamedevacademy.org/c-sharp-lesson-2-operators-variables-and-data-types/ Thu, 01 Sep 2016 23:29:33 +0000 https://html5hive.org/?p=1576 Read more]]> Hello and welcome to the Lesson 2 – Operator, Variables and Data Types on our tutorial series Learning C# with Zenva.

Tutorial Source Code

All of the source code for this tutorial can be downloaded here.

In this lesson, we are going to see two most used types of operators: arithmetic and logical/relational. In addition, we are going to learn about some data types in C# and what is and how to declare a variable. Last but not least, we are going to work with the data type string.

OPERATORS

Let’s see how Logical/Relational operators work, considering A = 5 and B = 10

image1

Now, considering A = 2 and B = 5

image2

A + B = 7;

A B = -3;

A * B = 10;

B / A = 2;

B % A = 1;

++A = 3;

– –B = 4;

DATA TYPES

A data type is a group of data with predefined characteristics in its value. Some example of these values are found on the table below:

image3

Source: https://gamedevacademy.org/zero-day-java-guide-1-installation-and-hello-variables/

VARIABLES

A variable is a name given to a storage area that our programs can manipulate. It can be local or attribute of a class. To declare a variable, we need to specify its type and name (<data_type> <variable_name>). In addition, there are some access modifiers we are going to learn in this lesson that are not so important now.
Each programming language has its own rules for naming variables. Here we have rules for giving a name to a variable in C#.

  • Variable names must begin with a letter of the alphabet;
  • Variables may contain letters and the digits 0 to 9. Not allowed: space or special characters, for instance ? ! @ # + – % ^ & *() [] {}.’;:”/ and \.
  • Variable names cannot be a Keywords belonging to C#. Example: continue, checked, public, return, etc;
  • C# is case sensitive, it means that var1 != Var1. (!= means different).

It is time to write some code using what we have learned so far. We are going to write examples using the Arithmetic Operator. Logical and Relational operators will be used as examples in lesson 4.

Open Visual Studio Community 2015, go to File -> New -> Project.
Installed -> Templates -> Visual C# -> Windows –> Console Application.

Name: Operators;
Location: Choose a location to save your project;
Solution name: Operators. Click OK.

Write or copy and paste the code below into Visual Studio code area.

using System;

namespace Operators
{
    public class Program
    {
        static void Main(string[] args)
        {
            int a;
            int b;

            a = 5;
            b = 10;

            Console.WriteLine("A + B = "+ (a + b));
            Console.WriteLine("A - B = "+ (a - b));
            Console.WriteLine("A * B = "+ (a * b));
            Console.WriteLine("B / A = "+ (b / a));
            Console.WriteLine("B % A = "+ (b % a));
            Console.WriteLine("Increase a = "+ ++a);
            Console.WriteLine("Decrease b = "+ --b);
            Console.Read();
        }
    }
}

Understanding new code:

int a; int b; = declaring a variable of type Integer.
a = 5; b = 10; = initializing variables.
Console.Writeln(“A + B”+ (a+b)); = after the string “A+B” we add the “+” (plus) to concatenate to a variable. Also, we wrote (a+b) inside a parentheses to indicate that this action performs first, and then we concatenate with the string. If we had writing (“A + B ”+ a+b), the results would be “ A + B = 510 ”. The program would concatenate a and b, not sum them.
Console.WriteLine(“Increase a = ” + ++a); = increasing variable “a”.
Console.WriteLine(“Decrease b = ” + –b); = decreasing variable “b”.

To save our application, click on Save Program or press Ctrl+ S.

To run the application we simple click on Start or press F5. Let’s run our application: F5

2.1

STRINGS

The data type string is so powerful that has its own class and also has some methods. In Lesson 5 we are going to learn more about classes and how to work with methods. We will have a preview of these contents here, but it is not our focus now. So, let’s begin!

String Properties

As I mentioned above, the class string holds methods and properties. When we declare a string, we can have access to its properties by pressing dot and our IDE will show us what methods and properties are accessible to use.

In the example below, we have chosen to use the property Length. This property gets the number of characters in the current string, including spaces.

Let’s write some code. Start a new project, name it Strings and write or copy and paste the code below.

using System;

namespace Strings
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = "Learning C# with Zenva!";

            Console.WriteLine("The length of str1 is:" + str1.Length);
            Console.Read();
         }
    }
}

In this example, I declared a str1 type string and initialized its value with a string, because it will only accept strings. Press F5 to run our application.

2.2

Note that to access the properties from the variable, in this case, string type, after the name of the variable, we put a dot(.) to see its properties and methods. In our example, we access the property “Length”.

String methods

Below we have a few methods that we can use with the String class. Some of these methods, we are going to write a the code for them using the structure conditional ‘IF’. This structure we are going to learn in Lesson 3 which wraps the flow control in C#.

Compare: This method compares two strings if they are equals or not and return 0 if it is true, else 1 if it is false.

Concat: This method concatenate two strings and return as resulst both strings together.

Contains: This method verify if there is a(some) word(s) in the current string I passed.

Replace: This method substitute a string to another.

ToUpper: This method gets the string I am calling this method from and return the same string but now in uppercase.

ToLower: This method gets the string I am calling this method from and return the same string but now in lowercase.

Trim: Removes the space of a string.

The table below show us some examples using these methods we learnt above.

Let’s consider we have two variables type string: str1 = “Learning C# with” and str2 = “ Zenva.”;

image6

Every method has a return. In italic is what the method returns and this returns will be explained in Lesson 5 – Methods, Exception Treatments, Classes and Object-Oriented

These are just a few examples of string methods. When writing code with the IDE Visual Studio, it shows us tips and how some methods, for example, work. Get used to started learning with Visual Studio too.

This is the end of this tutorial. I hope you have enjoyed and I see you in the next lesson!

Thank you!

]]>
C# Basic – Lesson 1: Installing Visual Studio and say “Hello World”! https://gamedevacademy.org/c-sharp-lesson-1-installing-visual-studio-and-say-hello-world/ Wed, 24 Aug 2016 08:20:49 +0000 https://html5hive.org/?p=1574 Read more]]> Hi, and welcome to the Lesson 1- Installing Visual Studio and say “Hello World” on our tutorial series Learning C# with Zenva.

Tutorial Source Code

All of the source code for this tutorial can be downloaded here.

In this lesson, we are going to download our IDE, Visual Studio Community 2015, learn how to install and configure it and write our first program that shows on the screen the sentence “Hello World”.

Before we get start, we need to know, what is an IDE?. IDE stands for Integrated Development Environment, in the computer area. An IDE is a software suite where developers can write and test their software. We will use Visual Studio Community 2015 as our IDE for these tutorial series.

Visual Studio is a powerful IDE from Microsoft. It not only has tools to create software since UI design, coding, testing and debugging, but also websites, applications, and services. Our focus in this course is to learn the language C#.

As I said, we will use C# as our programming language. ‘C-Sharp’ is an object-oriented language created by Microsoft. Based on C++ and JAVA, C# offers the same power as the C++ with the ease of Visual Basic programming. So, let’s get started!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

DOWNLOADING AND INSTALLING VISUAL STUDIO COMMUNITY 2015

Click here to visit Visual Studio website and click on ‘Download Community Free’.

C# Lesson 1 - 1

After download, execute it.

image2
Choose your installation location -> Select Default Installation -> Click Install.

image3

After the installation, if it asks for RESTART, please do it; otherwise, click LAUNCH.

When you open Visual Studio Community for the first time, it asks for Sign In. We can do it later. Now click on ‘Not now, maybe later’.

image4

Here you can you choose your color theme. I use Blue theme. You can change it later. After selecting your theme, click on Start Visual Studio.

image5
Here is where you can change your color theme inside Visual Studio. Tools -> Options -> Environment –> Color Theme

image6

image7
Congratulations. You have installed Visual Studio Community 2015. Let’s write our first code!

HELLO WORLD

To write our programs, we will use a simple console application. Follow the steps below to start writing our first program and run it in a console application.

File -> New -> Project.

image8

Installed -> Templates -> Visual C# -> Windows –> Console Application.

Name: HelloWorld;
Location: Choose a location to save your project;
Solution name: HelloWorld. Click OK.

image9

This is how it looks after you have clicked OK.

image10

Write or copy and paste the code below into Visual Studio code area. In the following tutorials, we are going to understand every single line of the program.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.WriteLine("Welcome to Learning C# with ZENVA!!");
            Console.Read();
        }
    }
}

Let’s understand what we wrote:

Console.WriteLine(): print a text and jump to another line.
Console.Read(): wait for the user to press a key to end the program.

The using  above everything  is a type of statement used to refer to a namespace that can be present in a dll in order to easily access classes that are within this namespace. In our case, we are using “System”. Without it, instead of writing Console.Writeline, we should write System.Console.Writeline.

To save our application, click on Save Program or press Ctrl+ S.

To run the application we simply click on Start or press F5. Let’s run our application.

1.1

Did you see how easy is that?

This is the end of this tutorial. I hope you have enjoyed and I see you in the next lesson!

Thank you!

]]>