Skip to main content

2.1 - Variables and Data Types

What Are Variables?

In programming, a variable is a named storage location in the computer's memory that holds a value. Think of variables as labeled containers that store data you can use and modify throughout your program.

Variables are fundamental to programming because they allow you to:

  • Store and retrieve data
  • Manipulate values
  • Track the state of your program
  • Make your code dynamic and responsive

Declaring Variables in C#

In C#, you must declare a variable before you can use it. Declaration involves specifying the variable's data type and name:

// Basic syntax for variable declaration
dataType variableName;

// Examples
int playerScore;
float enemySpeed;
string playerName;
bool isGameOver;

Variable Naming Rules and Conventions

When naming variables in C#, you must follow these rules:

  • Names can contain letters, digits, and the underscore character (_)
  • Names must begin with a letter or underscore
  • Names are case-sensitive (playerScore and PlayerScore are different variables)
  • Names cannot be C# keywords (like int, class, if, etc.)

Additionally, C# developers follow these conventions:

  • Use camelCase for local variables and private fields (e.g., playerHealth, enemyCount)
  • Use PascalCase for public properties (e.g., PlayerHealth, EnemyCount)
  • Choose descriptive names that clearly indicate the variable's purpose
  • Avoid abbreviations unless they're widely understood
// Good variable names
int playerScore;
float enemyMovementSpeed;
bool isPlayerAlive;

// Poor variable names
int ps; // Too short, not descriptive
float spd; // Unclear abbreviation
bool flag; // Doesn't indicate what the flag represents

Initializing Variables

You can assign a value to a variable when you declare it (initialization) or later in your code:

// Declaration with initialization
int playerScore = 0;

// Declaration first, assignment later
float enemySpeed;
enemySpeed = 3.5f;

Default Values

If you don't explicitly initialize a variable, it will have a default value depending on its type:

  • Numeric types (int, float, etc.): 0
  • bool: false
  • char: '\0' (null character)
  • Reference types (string, objects, etc.): null

However, local variables (variables declared inside a method) must be explicitly initialized before use.

Primitive Data Types (Value Types)

C# has several built-in primitive data types, which are also called value types because they directly contain their values.

Integer Types

Integer types store whole numbers without fractional parts:

TypeSizeRangeExample Use Case
byte1 byte0 to 255Small, non-negative numbers like RGB color components
short2 bytes-32,768 to 32,767Small ranges where int would be wasteful
int4 bytes-2,147,483,648 to 2,147,483,647Most whole numbers (default choice)
long8 bytes-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807Very large numbers like unique IDs
byte playerLevel = 60;
short itemCount = 1500;
int highScore = 10000000;
long uniquePlayerId = 9223372036854775807;

Floating-Point Types

Floating-point types store numbers with fractional parts:

TypeSizePrecisionExample Use Case
float4 bytes~7 digitsMost game physics, positions, rotations
double8 bytes~15-16 digitsScientific calculations requiring high precision
decimal16 bytes28-29 digitsFinancial calculations requiring exact precision
// Note the 'f' suffix for float literals
float playerSpeed = 5.5f;
double preciseCalculation = 3.141592653589793;
decimal moneyAmount = 1234.56m; // Note the 'm' suffix for decimal literals
Unity Relevance

Unity predominantly uses float for most values like positions, rotations, and physics calculations. The Vector3 type, which represents 3D positions and directions, uses three float values for X, Y, and Z coordinates.

Boolean Type

The bool type represents a boolean value that can be either true or false:

bool isPlayerAlive = true;
bool hasKey = false;

Boolean values are essential for controlling the flow of your program through conditional statements.

Character Type

The char type represents a single Unicode character:

char playerGrade = 'A';
char directionKey = 'W';

Note that character literals are enclosed in single quotes ('), unlike string literals which use double quotes (").

Reference Types

Unlike value types, reference types don't store their data directly. Instead, they store a reference (essentially an address) to the memory location where the data is kept.

The String Type

The most common reference type you'll use initially is string, which represents a sequence of characters:

string playerName = "Alex";
string gameTitle = "Adventure Quest";
string emptyString = "";

Even though string is a reference type, it has some special behaviors that make it seem like a value type in certain situations. We'll explore these differences more deeply in Module 5.

Type Inference with var

C# 3.0 introduced the var keyword, which allows the compiler to infer the type of a variable from its initialization expression:

// The compiler infers that playerName is a string
var playerName = "Alex";

// The compiler infers that score is an int
var score = 100;

// The compiler infers that isGameOver is a bool
var isGameOver = false;

Important notes about var:

  • The variable must be initialized when declared
  • Once the type is inferred, it cannot be changed
  • var is still statically typed—the type is determined at compile time, not runtime
  • var is most useful with complex types or when the type is obvious from the initialization
caution

While var can make your code more concise, it can also make it less readable if the type isn't obvious from the context. Use it judiciously.

Constants

When you have values that should never change during program execution, you can declare them as constants using the const keyword:

const int MaxPlayers = 4;
const float GravityAcceleration = 9.81f;
const string GameVersion = "1.0.0";

Constants:

  • Must be initialized when declared
  • Cannot be modified after initialization
  • Are evaluated at compile time, so they can only be assigned values that can be determined at compile time

Value Types vs. Reference Types: A Preview

We've introduced both value types (like int and float) and reference types (like string). Here's a brief preview of how they differ:

Value Types:

  • Store their data directly
  • When assigned to another variable, the value is copied
  • Each variable has its own copy of the data
int a = 10;
int b = a; // b gets a copy of a's value
a = 20; // Changing a doesn't affect b
// Now a is 20, but b is still 10

Reference Types:

  • Store a reference to their data
  • When assigned to another variable, the reference is copied (both variables refer to the same data)
  • Multiple variables can refer to the same data
// Simple example with strings (though strings have special behavior)
string name1 = "Player";
string name2 = name1; // name2 references the same string as name1

We'll explore this distinction more deeply in Module 5 when we discuss classes and objects.

Naming Conventions in Game Development

In game development, clear and consistent variable naming is particularly important. Here are some common patterns:

// Player-related variables
int playerHealth;
float playerSpeed;
bool isPlayerInvulnerable;

// Enemy-related variables
int enemyCount;
float enemySpawnRate;
bool areEnemiesActive;

// Game state variables
bool isGamePaused;
int currentLevel;
float timeRemaining;

Practical Example: Game Character Stats

Let's put these concepts together in a practical example for a game character:

// Character basic information
string characterName = "Elara";
int characterLevel = 5;
bool isAlive = true;

// Character stats
int healthPoints = 100;
int manaPoints = 50;
float movementSpeed = 3.5f;

// Equipment and inventory
string equippedWeapon = "Ancient Sword";
int goldCoins = 250;
byte potionCount = 3;

// Calculated stats
const int BaseAttackPower = 10;
int attackPower = BaseAttackPower + (characterLevel * 2);
float attackSpeed = 1.2f;
double damagePerSecond = attackPower * attackSpeed;

// Display character information
Console.WriteLine($"Character: {characterName} (Level {characterLevel})");
Console.WriteLine($"HP: {healthPoints}, MP: {manaPoints}");
Console.WriteLine($"Attack Power: {attackPower}, DPS: {damagePerSecond:F2}");

Conclusion

Variables and data types form the foundation of any C# program. By understanding how to declare, initialize, and use variables of different types, you've taken a crucial step in your programming journey.

In the next section, we'll explore operators in C#, which allow you to perform operations on these variables and create more complex expressions.

Unity Relevance

In Unity scripts, you'll use variables extensively to:

  • Store and modify game object properties (position, rotation, scale)
  • Track game state (score, health, ammo)
  • Configure components in the Inspector (by making variables public or using [SerializeField])
  • Communicate between different game objects and systems

Understanding variables and data types is essential for effective Unity development.