C Sharp/Variables

From Wikiversity
Jump to navigation Jump to search

Lesson Goals[edit]

This 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[edit]

A 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. Variables are very important for data manipulation. It would be hard to create a useful program that had no way of storing and manipulating different types of data. A computer variable is very similar to algebraic variables used in high school math. For example:

x = 5
y = 4x + 2

By using algebra we can solve for y. We can do this by first substituting the value of x into the equation, and then adding 2 to 4*x. The final result is 4*5 + 2 = 22.

The neat property of using a variable is that it is now possible to change the outcome of the algebraic equation by manipulating x. By changing x to 2 the equation is equal to 4*2 + 2 = 10. This allows a computer program to be able to perform extremely complex tasks.

The variable x in our algebraic equation represents a number. This number could be an integer (-1, 0, 2, 8) or a floating point number (2.1, 3.14159, 3/5). Human mathematicians are fairly good at determining what to do given any type of value for x. Computers are not as flexible, and they need to know what sort of value is being stored in a variable. For this reason, C# has a number of different types of variables.

Types[edit]

In 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[edit]

C# 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[edit]

using 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[edit]

The 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[edit]

Lets 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[edit]

It 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[edit]

using 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[edit]

Original area: 304.12
Truncated area: 304
Hit any key to end...

Remarks[edit]

int 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.

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[edit]

Topics in C#
Beginners Intermediate Advanced
Part of the School of Computer Science