Data and operators in C#: types, variables, input and output

Lesson 3 of 15 · C#

Every piece of data in a program is stored in a variable of a certain type. The type determines which values the variable can hold and which operations are allowed. This lesson covers the basic C# types, operators, keyboard input (Console.ReadLine), converting text into a number and nicely formatted output.

Before you start: required prior knowledge – your first application in Visual Studio.
How to learn: type in and run every example, and solve the tasks at the end on your own first; open the hint and the solution only after that. All programs are C# console applications (.NET 8 or later, without "top-level statements"); every one has been tested and gives the output shown.

Variables and constants

A variable must be declared before it is used: you write the type and then the name. The value is set with the assignment operator =, either immediately or later.

using System;

class Program
{
    static void Main()
    {
        int numberOfStudents;         // declaration
        numberOfStudents = 28;        // assigning a value
        double average = 4.37;        // declaration with an initial value
        char grade = 'A';             // a single character – single quotes
        bool passed = true;           // a logical value: true or false
        string name = "Maria";        // text – double quotes

        Console.WriteLine(name + " has an average of " + average);
        Console.WriteLine($"There are {numberOfStudents} students in the class.");
        Console.WriteLine($"Grade: {grade}, passed: {passed}");
    }
}

Text that starts with the $ sign is an interpolated string: an expression in curly brackets {…} is replaced with its value. This is a clearer way than joining the parts with the + operator. Notice that a logical value is printed as True, with a capital first letter.

A variable name starts with a letter or the _ sign; by convention local variables are written in camelCase (numberOfStudents), and methods and classes in PascalCase (WriteLine, Program). Upper-case and lower-case letters are different.

using System;

class Program
{
    static void Main()
    {
        var counter = 10;             // the compiler works out the type itself: int
        var message = "Hello";        // string
        const double PI = 3.14159;    // a constant – its value cannot be changed
        double r = 2;

        Console.WriteLine($"{message}! counter = {counter}");
        Console.WriteLine($"Circumference of the circle: {2 * r * PI}");
        // PI = 3;                    // error: a constant cannot be given a new value
    }
}

The keyword var does not mean "any type": the type is determined from the initial value and does not change afterwards. That is why var must always have an initial value.

Basic data types

TypeSizeValuesExample
int4 bytesabout ±2.1 billionint n = 150000;
long8 bytesabout ±9.2 · 1018long l = 8000000000;
double8 bytesreal numbers, about 15 significant digitsdouble d = 3.14;
decimal16 bytesexact decimal numbers (money)decimal c = 99.90m;
char2 bytesa single character (Unicode)char z = 'Ž';
bool1 bytetrue or falsebool ok = false;
string–text of any lengthstring s = "C#";

For whole numbers int is used most often, and when the values can go above 2 billion – long. For real numbers you use double, and for amounts of money decimal (the number ends with the letter m), because it stores decimal values exactly.

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine($"int:  {int.MinValue} .. {int.MaxValue}");
        Console.WriteLine($"long: {long.MinValue} .. {long.MaxValue}");
        int x = int.MaxValue;
        x = x + 1;                    // overflow: the result "wraps around" to the smallest int
        Console.WriteLine($"int.MaxValue + 1 = {x}");
        Console.WriteLine(0.1 + 0.2 == 0.3);       // double is not exact
        Console.WriteLine(0.1m + 0.2m == 0.3m);    // decimal is
    }
}
Watch out for overflow! C# does not report an error when a result does not fit in the type – the value silently "overflows". If you expect large numbers, use long.

Operators

The arithmetic operators are + - * / %. When both operands are whole numbers, / is integer division (the decimals are dropped), and % gives the remainder.

using System;

class Program
{
    static void Main()
    {
        int a = 17, b = 5;
        Console.WriteLine($"{a} + {b} = {a + b}");
        Console.WriteLine($"{a} - {b} = {a - b}");
        Console.WriteLine($"{a} * {b} = {a * b}");
        Console.WriteLine($"{a} / {b} = {a / b}");           // integer division
        Console.WriteLine($"{a} % {b} = {a % b}");           // remainder of the division
        Console.WriteLine($"{a} / {b} = {(double)a / b}");   // real division

        int n = 10;
        n += 5;                       // the same as n = n + 5
        n++;                          // increase by 1
        Console.WriteLine($"n = {n}");

        bool condition = a > b && b != 0; // relational and logical operators
        Console.WriteLine($"a > b and b != 0: {condition}");
        Console.WriteLine($"Square root of 2: {Math.Sqrt(2):F4}");
        Console.WriteLine($"2 to the power of 10: {Math.Pow(2, 10)}");
    }
}
KindOperatorsExample
relational== != < <= > >=x >= 18
logical&& (and), || (or), ! (not)x > 0 && x < 10
assignment= += -= *= /= %=sum += x
increment and decrement++ --i++

The Math class contains mathematical functions: Math.Sqrt, Math.Pow, Math.Abs, Math.Max, Math.Min, Math.Round and the constant Math.PI.

Keyboard input

Console.ReadLine() reads a whole line of text and returns it as a string. To get a number, we convert the text with the method int.Parse (or double.Parse, long.Parse…).

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter your name: ");         // Write does not move to a new line
        string name = Console.ReadLine();
        Console.Write("Enter your year of birth: ");
        int year = int.Parse(Console.ReadLine());   // text -> whole number
        int age = 2026 - year;
        Console.WriteLine($"{name}, this year you turn {age}.");
    }
}

When there are several numbers on the same line, the line is split into parts with the method Split, and each part is converted into a number:

using System;

class Program
{
    static void Main()
    {
        // input: 12 30
        string[] parts = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);
        int a = int.Parse(parts[0]);
        int b = int.Parse(parts[1]);
        Console.WriteLine($"Sum: {a + b}");
        Console.WriteLine($"Product: {a * b}");
    }
}

If the user enters something that is not a number, int.Parse stops the program with an error. int.TryParse is safer: it returns true if the conversion succeeded and writes the number into the variable after the word out.

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter a whole number: ");
        string input = Console.ReadLine();
        if (int.TryParse(input, out int number))   // success -> number has a value
            Console.WriteLine($"Doubled: {2 * number}");
        else
            Console.WriteLine($"\"{input}\" is not a whole number.");
    }
}

The if statement is explained in detail in the next lesson.

Conversions and formatted output

From a "smaller" to a "larger" type (for example int to long or double) the value is converted automatically. In the opposite direction you write an explicit conversion – the type in brackets – and part of the value can be lost.

using System;

class Program
{
    static void Main()
    {
        double price = 1499.75;
        int whole = (int)price;             // the decimals are dropped
        long big = whole;                   // int -> long happens automatically
        int fromString = int.Parse("250");
        string asString = 42.ToString();

        Console.WriteLine(whole);
        Console.WriteLine(big * 1000000);
        Console.WriteLine($"{Math.Round(2.5)} {Math.Round(3.5)}");  // rounding to an even number
        Console.WriteLine(fromString + 1);  // adding numbers
        Console.WriteLine(asString + 1);    // joining text
        Console.WriteLine($"{price:F1} dinars");    // one decimal place
        Console.WriteLine($"[{whole,8}]");          // width 8, aligned right
        Console.WriteLine($"[{"C#",-6}]");           // width 6, aligned left
    }
}

Math.Round rounds a value exactly in the middle towards the even number (2.5 → 2, and 3.5 → 4). For the rounding you learned at school, use Math.Round(x, MidpointRounding.AwayFromZero).

Decimal comma or point? Printing and reading real numbers depend on the computer's regional settings. If Windows uses, for example, Serbian settings, the program prints 1499,8 instead of 1499.8, and double.Parse expects a comma. The outputs in these lessons are shown with a point.
Special letters (such as č, ć, š, ž, đ) in the console. If question marks appear instead of them, add Console.OutputEncoding = System.Text.Encoding.UTF8; at the beginning of the Main method.

Practice tasks

Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.

TASK 01Difficulty: easy

Seconds into hours

Read a number of seconds n (0 ≤ n < 86400) and print the time in the form h:mm:ss – the minutes and seconds always with two digits.

Example 1

Input

3725

Output

1:02:05

Example 2

Input

86399

Output

23:59:59
TASK 02Difficulty: easy

The digits of a three-digit number

Read a three-digit number and print the sum of its digits and the number written with its digits in reverse order.

Example 1

Input

472

Output

Sum of digits: 13
Reversed: 274

Example 2

Input

105

Output

Sum of digits: 6
Reversed: 501
Common mistakes and tips
  • Text goes in double quotes ("A" is a string), and a character in single quotes ('A' is a char).
  • 7 / 2 is 3, while 7.0 / 2 or (double)7 / 2 is 3.5.
  • Console.ReadLine() always returns text – convert it into a number before calculating.
  • Use decimal for money, not double.

Check your knowledge

Open the quiz

Data and operators in C#

1. What is 17 / 5 if both numbers are of type int?




2. Which type is best for storing the price of a product?




3. What does Console.ReadLine() return?




4. What does int.TryParse do when the text is not a number?