Working with Variables in C#

One of the first things most new programmers learn how to do is work with variables. In this post I will discuss the different types of variables in C# and describe what they are, why they are used, and how to use them.

If you are already setup with Visual Studio or MonoDevelop on your computer, you can follow along with the post and run or modify the code snippets on your own. If you are using Windows and you don’t have a .NET IDE like Visual Studio or MonoDevelop installed, check out my post on how to get started using C# without Visual Studio.

What is a Variable?

A variable is a named storage location in memory that stores information that is often called a value. It is identified by a descriptive name that is created by the program developer(s) when the variable is declared. After it is declared and initialized, the developer(s) of the program can then use the name when they need to refer to the value it holds.

Along with storing and retrieving information, variables are also used to modify stored information and complete calculations and other tasks. For example, if you need to store the price of something like a grocery item, you could create a variable called bread or breadPrice and assign the actual price of bread at a grocery store as the value to the variable. Then if the price of bread ever changes, it can be updated to the new price. It can also be used in different calculations involving other grocery items or transactions.

How to Declare, Initialize, and Use Variables

Statements and syntax

When you declare a variable, you write a statement specifying it’s type, name, and value. A statement is a single instruction (or command) that performs an action. Regardless of what language is used, most programs are combinations and sequences of statements.

Statements are governed by a defined set of rules that describe how they can be constructed. These rules and conditions are usually known as syntax. Every programming language uses some form of syntax. Some more alike than others. The most important syntax rule in C# is ending all statements with a semicolon (;). For example, the semicolon at the end of this line that prints “Hello World!” allows the reader, compiler, or computer to know that the statement is over and the next one can be read:

Console.WriteLine("Hello World!");

Before we look at how to declare and use variables it’s important to look at their characteristics that are required in the syntax.

Characteristics of variables

As mentioned earlier, when you declare a variable, you specify 3 main characteristics:

  • Type - Defines the type of information stored in the variable. For example: char, int, string, etc.
  • Name - The name of the variable. Also known as an identifier. For example: firstName, lastName, age, etc.
  • Value - The information stored in the variable. For example: the character A, the integer 25, or the string Hello World.

Declaration of variables

The syntax to declare a variable in C# is:

<type> <name> [= <value>];

At initial declaration, specifying a value is optional. However in C# the syntax requires that varibles must be assigned a value before they can be used. If you try to use a variable before it is assigned a value your program will not compile. Here is an example of declaring variables:

string firstName;
string lastName;
int age;

After you’ve declared your variables, you can assign them values. You use the equal sign (=) as the assignment operator (I will cover operators in a future post) to assign the value to the variable. The values are always placed on the right-hand side of the assignment operator. Here is an example:

firstName = "Harry";
lastName = "Potter";
age = 17;

You can declare multiple variables of the same type at once then assign their values:

string firstName, lastName;
int points, assists, rebounds, blocks;

firstName = "Magic";
lastName = "Johnson";

points = 30;
assists = 16;
rebounds = 11;
blocks = 3;

You can also assign the same value to multiple variables of the same type:

string firstName, lastName;
int points, assists, rebounds, blocks;

firstName = lastName = "Johnson";
points = assists = rebounds = blocks = 3;

Initialization of variables

In programming the word initialization means to assign a value to a variable at the time it is declared. Here is an example:

string firstName = "Magic";
string lastName = "Johnson";

int points = 30;
int assists = 16;
int rebounds = 11;
int blocks = 3;

You can also initialize multiple variables of the same type at once:

int i = 2, j = 4, k = 6;
char a = '!', b = '@';
string helloStr = "Hello", worldStr = "World";

Using variables

There are many different ways that variables can be used. Here is an example of using variables in strings:

//  Declare and initialize string variables
string firstName = "Magic";
string lastName = "Johnson";

//  Declare and initialize integer variables
int points = 30;
int assists = 16;
int rebounds = 11;
int blocks = 3;

//  Print the player's name using variables
Console.WriteLine("Player: " + firstName + " " + lastName);

//  Print the player's game stats using variables
Console.WriteLine("Points: " + points + " | Assists: " + assists + 
" | Rebounds: " + rebounds + " | Blocks: " + blocks);

//  Output:
//  Player: Magic Johnson
//  Points: 30 | Assists: 16 | Rebounds: 11 | Blocks: 3

This example will show you how to modify the value of a variable, store the result of a calculation in a variable, and print the stored calculations:

//  Define variables
int num1 = 3;
int num2 = 10;

//  Change the value of num1
num1 = 5;

//  Create new variables and store results of calculations
int product = num1 * num2;
int quotient = num2 / num1;
int sum = num1 + num2;
int difference = num1 - num2;

//  Print the results
Console.WriteLine("Product = " + product);
Console.WriteLine("Quotient = " + quotient);
Console.WriteLine("Sum = " + sum);
Console.WriteLine("Difference = " + difference);

//  Output: 
//  Product = 50
//  Quotient = 2
//  Sum = 15
//  Difference = -5

Data Types

As you have seen variables are usually defined as a particular data type depending on the type of information that they will hold. Data types are similar sets of values with different ranges. There are two main data types in C#: value and reference types. I will cover the differences between value and reference types in another post. For this post I am going to focus on primitive types, which are usually value types themselves.

Characteristics of data types

There are 3 main characteristics of data types:

  • Name - The name of the data type. For example: char, int, string, etc.
  • Size - How much memory the data type uses. For example: 16 bits, 32 bits, 64 bits, etc.
  • Default value - The default value of the data type if it’s not initialized. For example: 0 or null

Primitive types

Some of the data types we just looked at are the most commonly used in C#. They are called primitive types. They are built into C# .NET. Here is a list of the most common primitive types and their characteristics:

Name Description Size Default value Range Example
int Integer numbers 32 bits 0 –2^31 through 2^31 – 1 int num = 4;
long Integer numbers (bigger range) 64 bits 0L –2^63 through 2^63 – 1 long num = 55L;
float Floating-point numbers 32 bits 0.0f ±1.5 x 10^–45 through ±3.4 x 10^38 float num = 0.23F;
double Double precision floating-point numbers 64 bits 0.0d ±5.0 x 10^–324 through ±1.7 x 10^308 double num = 2.5;
decimal Decimal numbers (for financial calculations) 128 bits 0.0m 28 significant figures decimal price = 1.75M;
string Sequence of characters 16 bits per char null N/A string name = "Bob";
char Single character 16 bits '\u0000' 0 through 2^16 – 1 char ch = '#';
bool Boolean (true or false) 8 bits false True or false bool flag = true;

Naming Variables

You must name your variables using the correct syntax in order for your programs to compile. As long as you follow the syntax rules, you can name a variable whatever you want, but it is important that you adopt a naming style that helps you and other programmers avoid confusion about what the variable is or what it’s for.

Rules

The main rules of naming variables are:

  • Names can only contain letters a-z and A-Z, digits 0-9, and the underscore character (_).
  • Names cannot start with a digit.
  • Names cannot be the same as a reserved keyword identifier.

You can view all of the reserved keywords in the Microsoft C# language reference.

Recommendations

When you name a variable, it is recommended that you choose a name that is descriptive of what the variable is used for. For example, if you needed to store a person’s full name, the variable name fullName would be a more appropriate choice than a variable name like variable123. Inappropriate variable names make a program more difficult to read and understand.

Variable names shouldn’t be too long or too short. Again, their main purpose should be to briefly describe what they are used for.

All variable names should be different with a different meaning. Don’t name variables that differ only by case or characters. For example, if you create two different variables and name one myVar and the other MyVar, you can easily get them confused with each other.

Even though it is legal in C#, I recommend not using the underscore character when you name variables. I think using camelCase notation is a better method and makes variables easier to read. Especially when declaring multiword variables. For example, thisCamelCaseVariable is easier to read than thisnoncamelcasevariable.

In closing I will end the post with a few more examples of some proper and improper variable names.

Proper names:

  • fullName
  • age
  • birthDate

Improper names:

  • 3cats (starts with digit won’t compile)
  • for (reserved keyword won’t compile)
  • time! (contains invalid character won’t compile)
  • myVar (compiles but ambiguous)
  • _address (compiles but underscore not necessary)
  • job_title (compiles but camelCase is more readable)
comments powered by Disqus