Skip to content

Chapter 2: Variables & Primitives - Integers, Doubles, and Storing Values

Theoretical Foundations

In the previous chapter, we learned how to make the computer speak to us using Console.WriteLine. We wrote strings—sequences of characters like "Hello, World!"—directly inside our code. While useful, that approach is static; the computer could only repeat exactly what we told it to say, word for word. To build dynamic applications, we need a way for the computer to remember information, perform calculations, and adapt its output based on changing values. This is where variables come in.

The Concept of Memory: The Warehouse Analogy

Imagine a massive warehouse with thousands of shelves. Each shelf has a unique label (like "Aisle 3, Shelf 2") and is designed to hold only one specific type of item: a box of apples, a gallon of milk, or a single number written on a sticky note.

In C#, a variable is like a labeled shelf in your computer's memory (RAM). When you create a variable, you are telling the computer: "Reserve a specific spot in the warehouse for me. I need to store a piece of information here, and I want to refer to it by this specific name."

The data type determines what kind of shelf you get. You cannot put a gallon of milk on a shelf designed for sticky notes; the shelf is too small, and the milk would spill. Similarly, C# is strict about what you can store in a variable. This strictness is called type safety. It prevents errors by ensuring you don't accidentally try to store text where a number should go.

Storing Whole Numbers: The int Type

The most common type of shelf in the warehouse is for integers. An integer is a whole number—positive, negative, or zero—without any decimal points. Examples include 5, -42, 1024, and 0.

In C#, we use the keyword int (short for integer) to declare a variable that holds whole numbers.

Declaring and Initializing There are two steps to using a variable:

  1. Declaration: Telling the computer the name and type of the variable.
  2. Initialization: Giving the variable its first value.

You can do these in one line:

using System;

// Declaration: We ask for a shelf labeled "age" that holds integers.
// Initialization: We put the number 25 on that shelf immediately.
int age = 25;

Or you can separate them (though this is less common for simple variables):

int score;      // Declaration
score = 100;    // Initialization (Assignment)

Reassignment Unlike a physical shelf, a variable can change its contents. You can put a different item on the same shelf later. This is called reassignment.

int score = 100;
Console.WriteLine(score); // Output: 100

// Later in the program...
score = 150; // Reassigning a new value to the existing variable
Console.WriteLine(score); // Output: 150

The Range of int Computers have limits. A shelf for an int is 32 bits wide (in standard C#). This means it can hold numbers roughly between -2,147,483,648 and 2,147,483,647. If you try to store a number larger than this (e.g., 3,000,000,000), you will cause an overflow. For beginners, assume int is large enough for counting things, ages, or scores.

Storing Decimal Numbers: The double Type

What if you need to store a value with a fractional part, like the price of an item ($19.99) or the temperature (98.6)? You cannot use an int because it discards everything after the decimal point.

C# provides the double type for floating-point numbers. A double (double-precision floating-point) is a shelf designed to hold numbers with decimal points.

Precision and Syntax A critical syntax rule for double is that you must include a decimal point. If you write 5, it is an integer. If you write 5.0, it is a double.

using System;

// Correct: 5.0 tells C# this is a decimal number
double temperature = 98.6;

// Incorrect (Conceptually): This is an integer, not a double
// double price = 5; // This might work due to implicit conversion, but it's bad practice for beginners to mix types.

The Nature of Floating-Point Math Computers store decimals in binary (base 2), which cannot perfectly represent all base-10 fractions. This leads to tiny precision errors.

For example, mathematically, 0.1 + 0.2 = 0.3. However, in computer memory, double types might represent this as 0.30000000000000004. This is not a bug; it is a fundamental limitation of how computers store floating-point numbers. For most AI and scientific applications, this tiny error is negligible, but it is something to be aware of.

Storing Text: The string Type

While int and double handle numbers, we also need to store text. In C#, text is stored in a string. A string is a sequence of characters (letters, digits, punctuation, spaces).

You learned about String Literals in Chapter 1. Now, we can store them in variables.

using System;

string message = "This is a string stored in a variable.";
string userName = "Alex";

Concatenation One of the most powerful features of strings is combining them. This is called concatenation. We can join a string literal with a variable's value using the + operator.

using System;

string greeting = "Hello";
string name = "Alice";

// Combining the string "Hello" with the variable name and a string literal
Console.WriteLine(greeting + ", " + name + "!");
// Output: Hello, Alice!

Storing Truth: The bool Type

Computers often need to make decisions based on whether something is true or false. For this, C# uses the bool type (short for boolean). A bool variable can only hold two possible values: true or false.

Think of a bool as a light switch: it is either on (true) or off (false).

using System;

bool isGameOver = false;
bool isServerOnline = true;

While we cannot use bool values to make logic decisions yet (like if statements, which are forbidden in this chapter), they are essential for storing the state of a system. For example, in an AI application, you might have a variable bool isModelLoaded = true; to track if a neural network has finished loading into memory.

Variable Naming Conventions

Just as physical shelves need clear labels, variables need clear names. C# enforces specific rules for naming:

  1. Allowed Characters: Names must start with a letter or an underscore (_). Subsequent characters can be letters, numbers, or underscores.
  2. Case Sensitivity: age and Age are two completely different variables.
  3. Reserved Keywords: You cannot name a variable int or class because those words are reserved for the language itself.

Conventions (Style) While not enforced by the compiler, professional developers follow style guides to make code readable.

  • Camel Case: Start with a lowercase letter and capitalize the first letter of each subsequent word (e.g., playerScore, userName, totalMoney). This is used for local variables.
  • Pascal Case: Start with an uppercase letter (e.g., Console). This is used for class names and methods, which we will cover later.

Assignment and Memory Visualization

The assignment operator (=) is the act of putting a value into a variable. It is not a mathematical equality; it is a directive. It reads: "Take the value on the right and store it in the variable on the left."

Here is how memory looks when we declare and assign variables:

The diagram visually demonstrates that the assignment operator (=) moves the value from the right side into the memory location defined by the variable on the left.
Hold "Ctrl" to enable pan & zoom

The diagram visually demonstrates that the assignment operator (`=`) moves the value from the right side into the memory location defined by the variable on the left.

Practical Application: AI Context

Why does this matter for Artificial Intelligence? AI models, particularly neural networks, are fundamentally mathematical engines. They process vast amounts of data using matrices of numbers.

  1. Weights and Biases: Inside a neural network, every connection between "neurons" has a weight—a decimal number that determines the strength of the connection. These weights are stored in variables of type double (or similar floating-point types). As the AI learns, these double values are constantly updated.

    • Example: double weight = 0.75;
  2. Counting Iterations: Training an AI model involves showing it data repeatedly (epochs). An int variable tracks which epoch the training is currently on.

    • Example: int currentEpoch = 1;
  3. Configuration Flags: When building an AI application, you often need to toggle features on or off, such as "Debug Mode" or "Use GPU." These are stored as bool variables.

    • Example: bool useGpuAcceleration = true;
  4. Logging and Metadata: Strings are used to store the names of data files, error messages, or the version of the model being used.

    • Example: string modelVersion = "v1.2.0";

Without the ability to store these values in variables, an AI program would be static, unable to learn or adapt. Every calculation would have to be hard-coded, making it impossible to train a model on new data.

Summary of Allowed Operations

In this chapter, we can only use the concepts listed in the "Allowed Concepts" section. This means we can:

  1. Declare variables (int, double, string, bool).
  2. Assign values to them using =.
  3. Output them to the console using Console.WriteLine (from Chapter 1) or Console.Write.

Complete Code Example (Allowed Concepts Only)

using System;

class Program
{
    static void Main()
    {
        // 1. Integer Variable (Whole Number)
        int userAge = 30;

        // 2. Double Variable (Decimal Number)
        double userHeight = 5.9;

        // 3. String Variable (Text)
        string userName = "Jordan";

        // 4. Boolean Variable (True/False)
        bool isSubscribed = true;

        // Outputting the variables using Console.WriteLine (Ch 1 Concept)
        Console.WriteLine("User Name: " + userName);
        Console.WriteLine("User Age: " + userAge);
        Console.WriteLine("User Height: " + userHeight);
        Console.WriteLine("Subscribed: " + isSubscribed);

        // Using Console.Write to stay on the same line
        Console.Write("Status: ");
        Console.WriteLine(isSubscribed); // Prints "True"
    }
}

By mastering these basic building blocks—storing numbers, text, and states—you establish the foundation for every complex program, from a simple calculator to a sophisticated AI system.

Basic Code Example

Here is a simple code example demonstrating how to store and display a person's age and name using variables.

using System;

class Program
{
    static void Main()
    {
        // --- Variable Declaration and Initialization ---

        // Declaring an integer variable to store age.
        // An 'int' is a whole number (no decimals).
        int age = 30;

        // Declaring a double variable to store a precise height.
        // A 'double' is a floating-point number (includes decimals).
        double height = 1.75;

        // Declaring a string variable to store a name.
        // A 'string' is a sequence of characters (text).
        string name = "Alice";

        // Declaring a boolean variable to store a student status.
        // A 'bool' can only be true or false.
        bool isStudent = false;

        // --- Displaying the Values ---

        // Using Console.WriteLine to output the variables to the console.
        // This method automatically adds a new line at the end.
        Console.WriteLine("--- User Profile ---");
        Console.WriteLine("Name: " + name);
        Console.WriteLine("Age: " + age);
        Console.WriteLine("Height: " + height + " meters");

        // Using Console.Write to output without a new line.
        // This keeps the cursor on the same line.
        Console.Write("Is a student? ");
        Console.WriteLine(isStudent);
    }
}

Explanation of the Code

  1. Variable Declaration: We start by telling the computer we want to create a storage location for data. We specify the data type first (like int, double, string, or bool). This is the "blueprint" for what kind of data can be stored there.
  2. Variable Naming: We give the variable a name (e.g., age, name). This is the label we use to refer to that specific piece of data later. We follow specific naming conventions, such as using camelCase for local variables (starting with a lowercase letter).
  3. Assignment: The = symbol is the assignment operator. It takes the value on the right (the literal value like 30 or "Alice") and stores it in the memory location defined by the variable name on the left.
  4. Type Safety: Because we declared age as an int, we cannot assign text like "Thirty" to it. The compiler enforces this type safety, preventing errors before the program even runs.
  5. Output: We use Console.WriteLine to print the values. When we use + with a string and another variable, C# automatically converts the variable's value into a string representation so it can be displayed.

Visualizing Memory

The following diagram illustrates how these variables are stored in memory.

When concatenating a string with a variable in C#, the diagram illustrates how the variable's value is automatically converted into a string representation before being stored in memory.
Hold "Ctrl" to enable pan & zoom

When concatenating a string with a variable in C#, the diagram illustrates how the variable's value is automatically converted into a string representation before being stored in memory.

Common Pitfalls

1. Forgetting the Semicolon (;) Every statement in C# must end with a semicolon. Missing one will cause a compiler error.

int age = 30  // Error: Missing semicolon
int age = 30; // Correct

2. Assigning the Wrong Type You cannot assign a value of one type to a variable of a different type if the conversion isn't allowed.

int age = "Thirty"; // Error: Cannot convert string to int

3. Using a Variable Before Initializing You must assign a value (initialize) a variable before you can use it.

int x;
Console.WriteLine(x); // Error: Use of unassigned local variable 'x'

The chapter continues with advanced code, exercises and solutions with analysis, you can find them on the ebook on Leanpub.com or Amazon



Code License: All code examples are released under the MIT License. Github repo.

Content Copyright: Copyright © 2026 Edgar Milvus | Privacy & Cookie Policy. All rights reserved.

All textual explanations, original diagrams, and illustrations are the intellectual property of the author. To support the maintenance of this site via AdSense, please read this content exclusively online. Copying, redistribution, or reproduction is strictly prohibited.