Lesson 3 - Variables, type system and parsing

In the previous lesson, Visual Studio and your first 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.


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.



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;

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


double a;
a = 56.6;

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 + "!";


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
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();


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;

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 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:

string s = Console.ReadLine();
int a = int.Parse(s);
a = a * 2;

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:

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


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.");

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:
Enter second number:
Addition: 5.86
Subtraction: 0.42
Multiplication: 8.5408
Division: 1.15441176470588

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, More on the type system: Data types, we'll talk some more about type systems, and introduce you all to more data types.




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



Article has been written for you by David Capka
Do you like this article?
3 votes
Previous article
Visual Studio and your first console application
All articles in this section
C# .NET basic constructs
Next article
Exercises for C# .NET lessons 1-3
Activities (23)




Fardeen HameedBaha:12/4/2016 2:00

Awesome Training Love It

Reply 12/4/2016 2:00

1 messages from 1 displayed.