Introduction
Variables are most important fundamentals of programming. it’s used to store your data. and any program that does anything real will use them. we’ll discuss how to make them in a C# program and how to put stuff in them, We will discuss the different types of variables that you can use.
What is Variable?
A core part of any programming language, and any program you make. is the ability to store information. For example a player’s score or the number of lives left.
You may remember discussing variables in math classes. but these are a little different. In math, we talk about variables being an “unknown quantity” for which you are supposed to solve. in other words, just something to figure out.
In programming, a variable is like a little bucket to put stuff in. You can put different things in the bucket. allowing the contents of the bucket to vary. (Hence the name, “variable”).
in C#, Like many other programming languages. there are many types of buckets, each of which can store different types of buckets, each of which can store different types of data. like numbers, characters, and so on. (While you probably don’t care too much at this point, languages that are like this are called “strongly typed”, some languages have essentially one type of bucket that anything can go in These are called “weakly typed” )
we’ll discuss the different types of C# variables in more detail in a minute. First, let’s look at the basics of how to create a variable.
Creating a Variables
// syntax:
Type Identifier;
int score;
Congratulations! You made your first Variable
To define a variable in C#, you generally follow two steps.
- the Declaration: you first specify the Data Type (the keyword) to tell the computer what kind of information you are storing.
- the Identifier: you then provide a Name for the variable, which acts as a unique label so you can reference that specific piece of data later in your code.
int is the Type
score is the Identifier
To Create a variable, you need two main parts followed by a semicolon:
- The Type( The category ) This tells the computer what kind of data the box can hold. For example, using the keyword
inttells the computer this box is Only for whole number (integers) like10,0,-5. You cannot put a decimal like (1.5) or a word in anintbox - The Name (The Label) : This is a name you choose to help humans understand what is inside. While math uses
x. programmers use descriptive names likeplayerScoreorenemyHealth. The computer doesn’t care about the name, but your teammates will!
Always choose names that describe the “data” perfectly. If you are strong the number of gold coins, name it goldCoins, not just g or number
Assigning Values to Variables
The next thing we want to do is give your new variable a value. This is called assigning a value to the variable and is done using the assignment operator =
int score = 0;
In Programming, the = sign usually means something a little different than it does in math. it doesn’t mean that two things are always equal; rather, it takes the value on the right side and stores it in the variable named on the left side. Think of a statement like this not as “score equals zero” but as “score is assigned that value of 0”.
of course you can assign any value to score;
score = 4;
score = 11;
score = 1564;
You can assign a value to a variable whenever you want. of course right now. we haven’t really learned very powerful tools for programming.
you can combine variable declaration with assignment in a single step
int theMeaningOfLife = 42;
This is quite common because you must assign a value to variable before you can read it contents back out. The first assignment to a variable is called initialization. so you might say that you cannot read the value in a variable until after it has been initialized.
The statement above makes a variable called theMeaningOfLife that can store int typed values and initializes it to the number 42.
Case sensitivity - A is not a
- Rule: If you name a variable
score, you must call itscoreevery single time.
int score = 0;
Console.WriteLine(Score); // mistake.
Console.WriteLine(score); // ok.
Types of Variables
There is more to life than just integers. Let’s take a look at the common variable types that we’ll see in a C# program and discuss the differences between them and when you’ll use them.
Here is a table containing the main variable types in C#
| Type Name | Description | Bytes | Data Range | Example |
|---|---|---|---|---|
| short | stores smaller integers | 2 | -32,768 to 32,767 | short score = 495; |
| int | stores medium-sized integers | 4 | -2,147,483,648 to 2,147,483,647 | int score = 450000; |
| long | stores very large integers | 8 | –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | long highScore = 4043333; |
| byte | stores small unsigned (no + or -) integers | 1 | 0 to 255 | byte color = 55; |
| ushort | stores small unsigned integers | 2 | 0 to 65,535 | ushort score = 495; |
| uint | stores medium unsigned integers | 4 | 0 to 4,294,967,295 | uint score = 4500000; |
| ulong | stores large unsigned integers | 8 | 0 to 18,446,744,073,709,551,615 | ulong highScore = 4043333; |
| float | stores smaller real (floating point) numbers | 4 | ±1.5 × 10^−45 to ±3.4 × 10^38, 7 digits of accuracy | float xPosition = 3.2f; |
| double | stores larger real numbers | 8 | ±5.0 × 10^−324 to ±1.7 × 10^308, 15 to 16 digits of accuracy | double yPosition = 3.3; |
| decimal | real numbers, smaller range, higher accuracy | 16 | ±1.0 × 10^−28 to ±7.9 × 10^28, 28 to 29 digits of accuracy | decimal zPosition = 3.3; |
| char | stores a single character or letter | 2 | any single character | char myFavoriteLetter = ‘c’; |
| string | stores a sequence of numbers, letters, or symbols | any | a sequence of any character of any length | string message = “Hello World!“ |
| bool | stores a true or false value | 1 | true or false | bool levelComplete = true; |
A variable is a “bucket” in memory. Because C# is Strongly Typed. you must choose the right bucket for the data you want to store.
1. The Integer Family (whole Number)
Used for counting things without decimals.
int: The “Standard” use this for almost everything (Scores, healthy, loop counters).short/long: useshortto save memory for small number; uselongfor massive numbers.- Unsigned (
uint,ushort,ulong): These ignore negative signs. This lets them store positive numbers twice as large as their signed versions. byte: Smallest bucket( 0 to 255). Used for “raw data” like images, files, or network data.
2.The Floating-point family (Decimals)
Used for “Real Numbers” (eg. 3.5, - 10.3).
floatThe Game Dev standard. Fast and efficient for positions and speeds.doubleLarge and more precise. Used to high-level math.decimalThe Money type. Extremely accurate but slower; used for financial calculations where rounding errors are not allowed.
3. Text and Logic
char: Exactly one letter or symbol ( use single quotes `A’).strting: A sequence of text (uses double quotes:"Hello").bool: A logic switch. can only betrueorfalse.
Systemic (Static) vs. Dynamic Languages.
You asked where to add the difference between language types. Here is a clear breakdown to add to Your “What is a variables? ” section:
Statically Typed (C# system):
- The Rule You must declare the type before using the variable (e.g:
int x:). - The Result: The bucket never changes . Your cannot put a word into an
intbucket later. - Benefit: The computer catches errors be fore the program even runs.
Dynamically Typed (eg. Python, Javascript)
The Rule: You don’t’ have to specify a type. You just create a variable name.The Result: The bucket is “Flexible”. It can hold a number now and a sentence later.Benefit: Faster to write, but harder to find bugs because the computer doesn’t check the “bucket” unity the program is already running.
Guide to Good Variable Names
there’s a lot of debate in the programming world about what makes for a good variable name, and I’m going o give you my ideas here.
The motivation for good variable name is to make it easy for someone else to read and understand your code or even for you to understand your code when you come back to it a week, month, or year later.
Quote: When i first wrote this code, only me and God knew what it did. Now, only God Knows!
Good variable names are an absolutely critical part of writing readable code and are not something to e ignored.
1: There are some build-in rules for variable naming in C#:
- Start with a letter Must begin with
'a-z', 'A-Z'or an underscore_ - No numbers at the start: You can use numbers inside the name, but not as the first character.
- No Spaces: The compiler will break Use
playerScoreinstead ofplayer score.
2. The C# Standards: camelCase
-
To make words stand out without spaces, use camelCase.
-
How to do it: Start with a lowercase letter, then capitalize the first letter of every following word.
-
PlayerScore(okay) -
remainingLivesLeft(okay) -
playerscore(hard to read)
**3. The professional Guidelines ( Best Practices)
- Be Descriptive: name it exactly what it is use
goldCoins, notgorgc. - Avoid Abbreviation: Don’t use
plrscrwhen you can useplayerScore. if you have to stop and “guess” what it means, the name is too short. - The 3-letter minimum: Most good names need at least 3 letters to be clear ( Exceptions:
xandyfor coordinates). - Avoid “Number-Ending” : Instead of
count1andcount2, use specific names likerowCountandcolumnCount.
Printing the Content of Variables
Any of these variables can be written out in a way similar to what we did in the previous tutorial,
Console.WriteLine.
int score = 35;
Console.WriteLine(score);
bool levelComplete = true;
Console.WriteLine(levelComplete);
string message = "Hello World!";
Console.WriteLine(message);
Example
// - Text type.
string playerName = "Iron Kight";
char rankGrade = 'A';
// - whole number
int healthPoints = 100;
uint goldCoins = 550; // unsigned because gold can't be negative!
byte level = 5; // small number (0-255) saves memory.
// - decmila numbers.
float movementSpeed = 5.5f // note the 'f' at the end!
double worldXCoord = 1240.5523;
// - logic (Boolean)
bool isAilve = true;
// - printing to the console.
Console.WriteLine("--- character profile ---");
Console.WriteLine("Name: " + playerName);
Console.WriteLine("Rank: " + randGrade);
Console.WriteLine("Level: " + level);
Console.WriteLine("Health: " + healthPoitns);
Console.WriteLine("Gold: " + goldCoins);
Console.WriteLine("Is the player alive? " + isAlive);
Console.WriteLine("--------------------------------");
Summary
- Variables store all sorts of stuff:
byte,short,intandlongstore integer values of 1 byte, 2 byte, 4 bytes and 8 bytes respectively.floatanddoublestore floating point values using 4 bytes and 8 bytes respectively.decimalstores floating point values with 16 bytes, with a smaller range and more accuracy thandoublecharstores text.boolstores a true or false value.
- You declare a variable by starting its type and a name like this:
int aNumber; - Name must start with a letter ( a - z , A - Z) , can contain any letters, numbers and the underscore (
_) character, and can be basically any length. - You can assign values to variables using the equal (
=) sign like this:aNumber = 3; - You can declare a variable and assign it a value all in one statement, like this:
int anotherNumber = 5