C Sharp/Variables
Lesson Goals
editThis lesson will focus on the creation and use of different variables in C#. At the end of this lesson you should be able to:
- Understand what a variable is.
- Understand the basic C# types.
- Create variables of different types.
- Assign values to those variables.
- Cast from one variable type to another.
Variables
editA variable is a place in memory where the application can store some type of information. This information can be a number, a string, a class, a delegate, or even a custom data type.
The primary concept of variables is the naming conventions:
- The only valid characters of a variable is English alphabet (A to Z and a to z), digits (0 to 9) and underscore character (_)
- The name cannot start by a digit
For example names like "Hello", "a1234", "_variable", "is_good", "zXYzz" are valid, but "1bac", "C#", "hello world", "invalid.var" are invalid.
Types
editIn the above algebraic example, we have taken for granted that x can actually store a number. Programming languages such as C# have types associated with their variables. Here is a list of all the types in C#.
Type | Size (in bits) | Range |
---|---|---|
bool | 1 | false or true |
sbyte | 8 | -128 to 127 |
byte | 8 | 0 to 255 |
short | 16 | -32768 to 32767 |
ushort | 16 | 0 to 65535 |
int | 32 | -2147483648 to 2147483647 |
uint | 32 | 0 to 4294967295 |
long | 64 | -9223372036854775808 to 9223372036854775807 |
ulong | 64 | 0 to 18446744073709551615 |
char | 16 | 0 to 65535 |
float | 32 | 1.5 x 10-45 to 3.4 x 1038 (7 digits precision) |
double | 64 | 5.0 x 10-324 to 1.7 x 10308 (15-16 digits precision) |
decimal | 128 | 1.0 x 10-28 to 7.9 x 1028 (28-29 digits precision) |
Variable Instantiation
editC# has a common method for the creation of variables.
type name;
Where type is the "type" of variable to initialize. "name" is a custom name that the programmer assigns the variable. Lets declare our variable x from above.
int x = 5;
The above code not only creates a variable x that can store a number (as specified by int), but it also stores a value of 5 into that variable. So now whenever we call the variable x the computer will see that as a value of 5.
You can also assign values to your variables at any point in the program. This can be done with the = operator.
int x = 0;
x = 5;
The above code will create a variable named x that can store an integer number (as specified by int). The initial value of x is zero. However we change the value of x to 5 at the second line of code.
Code Example 1
editusing System;
namespace VariablesExampleOne
{
class Program
{
static void Main(string[] args)
{
int x = 0;
Console.WriteLine("The variable x contains " + x);
x = 5;
Console.WriteLine("The variable x contains " + x);
int y = 2;
Console.WriteLine("The variable y contains " + y);
float z = 2.4f;
Console.WriteLine("The variable z contains " + z);
Console.WriteLine("The integer cast of z is " + (int)z);
Console.WriteLine("Hit any key to end...");
Console.ReadKey();
}
}
}
Output
editThe variable x contains 0 The variable x contains 5 The variable y contains 2 The variable z contains 2.4 The integer cast of z is 2 Hit any key to end...
Remarks
editLets step through this code one line at a time.
int x = 0;
This line initialized a new integer named x. The initial value of x is set to zero. If we did not define this initial value to zero, then the program would not compile properly.
Console.WriteLine("The variable x contains " + x);
This line outputs some data to the console. This line in particular prints the value of x on the screen. The operator + performs a string concatenation. This means the string value of x is appended to the end of the text and then displayed in the console.
x = 5;
Console.WriteLine("The variable x contains " + x);
Next we've reassigned the value of x. We no longer need the keyword int because we've already told the compiler that we'd like a variable named x. After reassigning the value of x to 5, we then output this to the screen.
int y = 2;
Console.WriteLine("The variable y contains " + y);
Next we've created a new variable named y. This variable is initialized to 2. The purpose of this code is to show that your variable can be initialized to whatever you'd like. The result is then output to the console.
float z = 2.4f;
Console.WriteLine("The variable z contains " + z);
Here we've created a new variable type. A float can store non-integer numbers. We've initialized this float to 2.4f. The f is to inform the compiler that 2.4f is a floating point value. If we'd used 2.4 instead of 2.4f then the compiler would have assumed that 2.4 represented a double. It would have then thrown an error, because the compiler is not sure how to convert a double to a float without help from the programmer.
Console.WriteLine("The integer cast of z is " + (int)z);
Here we've casted the floating point value of 2.4f to an integer. This will remove any precision after the decimal place (as we can see on the output).
Console.WriteLine("Hit any key to end...");
Console.ReadKey();
These lines of code pause the execution of the program. Without these lines the program would terminate very quickly, and we wouldn't be able to view the program output. Console.ReadyKey() waits until the user presses a key.
Casting
editIt is often important to be able to convert between different types of data. For example, the user may request a double precision value from your program, but your program stores them as floats. The requires a conversion method between types. This conversion is accomplished via casting. The syntax for casting is as follows:
(type)name
Where type is the type to convert to, and name is the name of the variable to convert.
Code Example 2
editusing System;
namespace VariablesExampleTwo
{
class Program
{
static void Main(string[] args)
{
float area = 304.12f;
int truncated = (int)area;
Console.WriteLine("Original area: " + area);
Console.WriteLine("Truncated area: " + truncated);
Console.WriteLine("Hit any key to end...");
Console.ReadKey();
}
}
}
Output
editOriginal area: 304.12 Truncated area: 304 Hit any key to end...
Remarks
editint truncated = (int)area;
This line of code performs a type cast on the floating point variable named area. It is important to note that a cast does not change the contents of the variable area. Instead, a new integer value of area is created and stored in the variable truncated. The name truncated comes from the fact that this type of conversion (from float to int) removes any precision past the decimal place. This is called truncating.
String
editString is any sequence of characters, without limitation of character. String can be empty. Some examples are:
string s1 = "123Hello World Guys!";
string s2 = "ñ♥☺♫";
Console.WriteLine("Hello " + s1);
Console.Write("My name is {0}", s2);
In order to convert string to a number (int or double) we use these expressions:
string s = "3.14";
double a = double.Parse(s);
Console.WriteLine(a);
string s2 = "-654";
int b = int.Parse(s2);
Console.WriteLine(b);
For the opposite usage, we use ToString(n). For example:
int n = 5;
string s3 = "My number is: " + n.ToString();
var keyword
editIf a variable's type is clear according to the code, we can simply use "var" for its type. For example is these statements:
var a = 5;
var v = "Hello World";
But this statement is wrong:
var a;
because the compiler cannot understand what type of variable it is. Also, you cannot define a field (variable of a class) by var.
Summary
edit- Variables are used to store different types of data in C#.
- C# has many types. Commonly used types include int, float and bool.
- Each variable is given a unique name by the programmer. The name should reflect the type of data that is being stored. Words such as Area and IsValid are more descriptive than t_var1e. Using descriptive variable names can help with code comprehension.
- Casting between basic types is possible using the syntax
(type)name
- Casting can introduce problems if the destination data type causes a loss of information. An example is when converting from a float to an int. The float will be truncated to remove any precision after the decimal place. This causes a loss of data and it is important that the program be robust enough to deal with the loss of data accordingly.
Practice Exercises
edit- Create a program that can convert a double to an int and then back to a double. What is the final value of your variable? Did you expect this outcome? Make lots of explanatory console outputs so that you can better understand what is going on at each step of your code.
- Create a program that converts from an int to a char. What happens when you output this char to the screen using Console.WriteLine?
Where To Go Next
editTopics in C# | ||
Beginners | Intermediate | Advanced |
---|---|---|
Part of the School of Computer Science |