Get up to 80 % extra points for free! More info:

Lesson 3 - Variables, type system and parsing in C# .NET

Lesson highlights

Are you looking for a quick reference on variables, type system and parsing instead of a thorough-full lesson? Here it is:

Creating an int variable (for whole numbers) and assigning a value 56 to it:

int a = 56;
Console.WriteLine(a);
Console.ReadKey();

Reading text from the console using Console.ReadLine() and concatenating strings with +:

Console.WriteLine("Write something: ");
string input = Console.ReadLine();
Console.WriteLine("You wrote: " + input);
Console.ReadKey();

Reading numbers from the console using Parse() method to make a number from text:

Console.WriteLine("Enter a number and I'll double it: ");
string s = Console.ReadLine();
int a = int.Parse(s);
a = a * 2;
Console.WriteLine(a);
Console.ReadKey();

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, Visual Studio and your first C# .NET console application, we learned how to work with Visual Studio, and created our first console application. In today's lesson, we're going to look at the so-called type system of C# .NET. We'll introduce basic data types, and we'll work with variables. As a result, we'll create 4 simple programs, including a simple calculator.

Variables

Before we start with data types, let's make sure we understand what a variable is, if you're already familiar with programming, please excuse the short explanation. Surely, you remember variables from Math class (e.g. X), in which we could store some value, usually a number. A variable in IT is really the same thing. It's a place in computer memory where we can store some data, e.g. a username, the current time or a database of articles. This place has a certain reserved size, different variable types have different sizes, which the variable can't exceed, e.g. an integer number can't be greater than 2 147 483 647.

A variable is always of some sort of data type. It can be a number, a character, text, etc. It depends on what we want to use it for. Before working with a variable, we have to declare it first to specify how this variable will be called and of what data type it will be. The programming language will establish it in the memory, and be able to use it. Our computer knows, based on our declaration, how much memory the variable occupies and how to operate with that piece of memory.

Type system

There are two basic type systems: static and dynamic.

In the dynamic type system, we're fully relieved from the fact that the variable has some data type at all. Obviously, the variables have types internally, but the language doesn't show it. Dynamic typing often goes so far that we don't have to declare variables at all. If we store some data in a variable and the language finds out that this variable had never been declared, it'll just create it automatically. In the same variable, we are able to store text, user objects or decimal numbers. The language will automatically change the inner data type according to data we're assigning into the variable. Due to a smaller amount of code, the development is usually faster in those languages. The example languages with this kind of type system are e.g. PHP or Ruby.

On the other hand, we have the static type system. It requires us to declare the variable type, and this type is unchangeable from then on. Meaning that, if we try to store a user object into a string, we'll get yelled at by the compiler.

C# is a statically typed language. All variables must be declared as specific data types. The disadvantage to this is that due to the declarations a source code is a bit longer and it takes more time to write it. The great advantage is that before running, the compiler checks whether all data types match. The dynamic typing may look advantageous, but we can't automatically check the source code and if we expect a user object somewhere and we get a decimal number instead, the error will be revealed only during the run-time and the interpreter will stop the program. C# won't allow us to compile a program until it checks it for errors (this is yet another benefit to using compilers).

Let's make a sample program, so that you'll be able to apply this newly acquired knowledge. We'll continue with the theoretic part of it all next time. Here are three basic data types:

  • Numbers: int
  • Real numbers (10.12, ...): double
  • Texts: string

Variable printing program

We'll go ahead and declare an integer variable, name it a, store the number 56 in it, and print its value to the console. Create a new project and name it Output (we'll create a new project for each sample program). Don't forget to write the code inside the body of the Main() method like we did last time, I won't copy the Main() method here anymore.

int a;
a = 56;
Console.WriteLine(a);
Console.ReadKey();

The first command declares a new variable, a, of the int data type. This variable will be used to store integers i.e. whole numbers. The second command assigns a value to the variable using the = operator we all know from math classes. The last command is already familiar to us. It prints the content of the variable a. The Console is smart and knows how to print numeric values as well. ReadKey() just waits for user input, and ends the program.

Console application
56

The same code for a real number variable would look like this:

double a;
a = 56.6;
Console.WriteLine(a);
Console.ReadKey();

It's almost the same as the code for integer. The decimal separator will always be represented by a dot here (.). Even if your regional separator is a comma.

Parrot program

The previous program was a bit boring, let's try to respond to user input somehow. Let's write a program named Parrot. You can probably guess what it will do - it will repeat (twice) what the user has written. We haven't tried to read anything from the console yet, but it's very simple. There is the ReadLine() method that returns a string from the console. Let's write the following code:

Console.WriteLine("Hi I'm Lora, the virtual parrot, and I love to repeat!");
Console.WriteLine("Type something in: ");

string input;
input = Console.ReadLine();

string output;
output = input + ", " + input + "!";

Console.WriteLine(output);
Console.ReadKey();

It's a little more fun, right? :) The first two lines are self-explanatory (they just print text). On the third line, we declare a string input. Input will contain the return value of the ReadLine() method, i.e. whatever the user enters into the console. To make the code more understandable, we create another string variable for output. The interesting part of the code is when we assign the value to output, we do a string concatenation. We use the + operator to join several strings into one. As you can see, it doesn't matter whether it's a variable or it's an explicitly declared string in quotation marks in our source code. We assign the input to the variable, then a comma followed by a space, then input again and finally an exclamation mark. Then the program will display this variable, and wait for the user to press any key before terminating.

Console application
Hi I'm Lora, the virtual parrot, and I love to repeat!
Say something:
Lora wants a cracker!
Lora wants a cracker!, Lora wants a cracker!!

We can assign values to variables right in their declaration, so we could replace:

string input;
input = Console.ReadLine();

with:

string input = Console.ReadLine();

We could shorten the program in many other ways, but generally, it's better to use more variables and focus on clarity and readability than altering the code until we forget what the program was even supposed to do.

Doubler program

The doubler program will retrieve an input number, double it and display the result. With the current knowledge we possess, we could write something like this:

Console.WriteLine("Enter a number and I'll double it: ");
int a = Console.ReadLine();
a = a * 2;
Console.WriteLine(a);
Console.ReadKey();

C# will report an error and highlight the line on which we tried to get the value from the console and store it into the int variable. We've just seen type checking in action, ReadLine() returns a string, and we're trying to assign it to the int variable. We need to parse it first. Everything from the console is text, even if we enter a number.

Parsing

Parsing means converting from text to another specific type, e.g. numbers. Many data types in C# already have methods for parsing prepared. Since we want to parse an int from string, we'll write the following:

string s = "56";
int a = int.Parse(s);

We can see that the int data type has a Parse() method that takes a string parameter and returns a number. Let's apply this knowledge to our program:

Console.WriteLine("Enter a number and I'll double it: ");
string s = Console.ReadLine();
int a = int.Parse(s);
a = a * 2;
Console.WriteLine(a);
Console.ReadKey();

The first thing we did was store the text from the console into the string s. Integer variable a will then, thanks to parsing, contain the numeric value of the string s. Then, we double the value of a and print it out to the console.

Console application
Enter a number and I'll double it:
1024
2048

Note: You may encounter parsing from string to numerical values when using the Convert class. However, it's mainly meant for conversion between numbers and cannot deal with text properly.

Parsing can't be done if a word is used instead of a number in the text, but don't worry about these sort of scenarios for now.

Simple calculator

Since we haven't worked with real numbers yet, let's program a simple calculator. It'll be very easy. The input will consist of two numbers, and the program will display the results of addition, subtraction, multiplication, and division.

Console.WriteLine("Welcome to calculator!");
Console.WriteLine("Enter first number:");
double a = double.Parse(Console.ReadLine());
Console.WriteLine("Enter second number:");
double b = double.Parse(Console.ReadLine());
double sum = a + b;
double difference = a - b;
double product = a * b;
double quotient = a / b;
Console.WriteLine("Addition: " + sum);
Console.WriteLine("Subtraction: " + difference);
Console.WriteLine("Multiplication: " + product);
Console.WriteLine("Division: " + quotient);
Console.WriteLine("Thank you for using calculator. Press any key to end the program.");
Console.ReadKey();

Note: The decimal separator depends on your regional settings, for the English-speaking world it would be a dot.

Console application
Welcome to calculator!
Enter first number:
3.14
Enter second number:
2.72
Addition: 5.86
Subtraction: 0.42
Multiplication: 8.5408
Division: 1.15441176470588
Thank you for using calculator. Press any key to end the program.

First, we simplified parsing from the console, so we don't need a string variable (we wouldn't use it further anyway). Secondly, at the end of the program, we join a string with a number using the plus sign (+). C# will surprisingly not report an error, but it'll perform an implicit conversion from a number to a string (using the ToString() method). If it wasn't this way or if we got into a situation where we needed to convert anything to string, we'd call the ToString() method on the variable. In this case, C# called it for us, it basically did this:

Console.WriteLine("Addition:" + sum.ToString());

Now we just did the opposite of parsing - conversion from anything to a string. In the next lesson, Solved tasks for C# .NET lessons 1-3, we'll talk some more about type systems, and introduce you all to more data types.

All of the programs are available for download in the attachment below. You should definitely try to create some programs similar to these, seeing as how you already have the knowledge necessary to do so! :)

In the following exercise, Solved tasks for C# .NET lessons 1-3, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 108x (132.17 kB)
Application includes source codes in language C#

 

Previous article
Visual Studio and your first C# .NET console application
All articles in this section
C# .NET Basic Constructs
Skip article
(not recommended)
Solved tasks for C# .NET lessons 1-3
Article has been written for you by David Capka Hartinger
Avatar
User rating:
31 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities