C# Basic Tutorials - Data Types & Type Conversion
Watch the video or follow the tutorial.
In this tutorial we will have a little look at data types and type conversion in C#. If you have not already installed Visual Studio then have a look at my first tutorial and when you're ready you can come back here and continue from where you left off. So, open Visual Studio and create a new project using the Visual C#/Windows Classic Desktop/Windows Forms App(.NET Framework).
Name the project DataTypes and press OK, changing the location to wherever you want to save the files to.
Click on the Toolbox label on the left hand side and double click on the Button control. In the main window for the project reposition and resize the Button control until it looks as below. You change the text on the Button from the Text property by selecting the button and in the properties window at the bottom right of the screen scroll down until you see the Text property and the change the text from "button1" to "Test", you can also change the Font size to something bigger too.
Double left-click on the Button control and it will open the code window with the Button click event function already written. This is where we will write the code that we want to run when the button is clicked.
Now that we have our project ready we can begin looking at the basic data types used in C#.
Basic C# Data Types
• Value Types
A variable is assigned a value directly such as
int x = 9;
Here there is a single location in memory that holds the value 9.
• Reference Types
A variable points to a location in memory and returns whatever is at that location
Form f = new Form();
This is the creation of an instance of the Form class object so there are two locations in memory, one for the Form class and one for the instance of the form class f. The object Form is therefore accessed by reference through the instance of the class f.
This example would be more correctly written as:
F = new Form();
• Pointer Types
Pointer type which are variables that store the memory address of one of the other two data types
And if you’ve used pointers in C or C++ then all you need to know is that Pointers in C# have the same capabilities as the pointers in those two other languages. An example of which would be:
unsafe char* charptr;
Which says the variable charptr is a created as a pointer to a char object but in C# it has to be used in the unsafe context. I never really use pointers like this in C# but they are available if you ever feel the need.
Next we will have a look at some basic data types
First of all we have the basic binary data type…..the Boolean which is either 0 or 1, or as the case in C# True or False with True representing 1 and False representing 0.
Computers use the binary numbering system because of the way they work. Computer CPUs use the transistor as their basic component and the transistor is a simple electric circuit that is basically a switch. It either lets electricity through, if the applied voltage is high enough or it blocks it if the applied voltage is too low. So, the signal seen at the transistor is either on or off and this is translated by the software to be 1 for on and 0 for off. That is that basic way a computer works and since there tends to be millions of single transistors on a single CPU it gives the computer the ability to be a very powerful mathematical computing system.
As an example of a couple of the basic C# data types outlined above I will discuss two that I regularly use. The Integer type int is probably the most commonly used data type since I use it for all manner of counters and loop iterations and it is the standard go to value holder that I normally use. The next most basic building block used in binary is the byte which is 8 bits, 8 1s and 0s in a row. This setup allows for 2^8 = 2*2*2*2*2*2*2*2 = 256 possible unique combinations of 1s and 0s and so a byte has 256 possible values. An int uses 32 bits so 4 bytes which is equal to 2^32 = 4,294,967,295 possible values. This makes the int available for pretty much most calculations that you will do in a basic C# program.
Another data type that is not in the above list that I will talk about it the character data type: char.
The char uses 16 bits – 2 bytes to represent a particular Unicode character. This allows it to hold up to 65,535 letters, as far as I know the letters from pretty much all modern languages from around the world, although I could be wrong. This means that using Unicode chars you can port your app to any language you wish so long as you understand the syntax. To create a char object you would type:
char s1 = Char.ConvertFromUtf32(0x0041); // Latin Capital Letter A
Strings are basically just character arrays that are capable of holding more than enough characters so you will never run out of space. I think I remember reading somewhere that the maximum number of values that a string can old is something like 2 billion or there abouts, some have said that it is only limited by available memory, whatever the truth of the matter is I guarantee you will run out of things to say before you run out of space in your string.
With strings there are a couple of points to make about special characters like tab and newline in C#. Use the backslash character and the associated letter to insert a particular special character. Special Characters can be entered into a string with a backslash, for example:
string strText = "Start\tTab\r\nForNewLine";
Other special characters of note are \’ for a single quotation mark and \” for a double quotation mark. You can use “\\” to enter a backslash character into your string but you can also use the @ character, as follows:
string strText = @"C:\Users\Alan\Desktop\File.txt";
The @ character can be used to tell the application that a backslash can be entered without the use of the second backslash as seen here. The @ character will also preserve any newline characters in the string and so:
string strText = @"This series of tutorials
will teach us about C#
This way of doing it also allows the use of quotation marks as follows:
string strText = @"I was told to: ""Go over there""";
As with all variables it is a good idea to initialise them when they are created and a good way to do this is with the string.Empty object. This is done as follows:
string strText = String.Empty;
This prevents a NullReferenceException occurring when you first use the variable.
If a variable will hold a value that will never change, you can use the constant keyword const which will ensure that if any attempt to change the value occurs an error will be thrown and with proper error capture in place this can be easily managed so the program doesn’t crash or exit.
const string strConstString = "I will never change";
const int intConstInteger = 101
We will now have a little look at Type conversion between data types. Type conversion is converting one type of data to another type. It is also known as Type Casting. Most conversions can be done explicitly by users using the pre-defined functions given in C#.NET. The following example shows how to typecast in C#:
int x = 900;
double y = 100.1;
double y1 = (double)x;
int x1 = (int)y;
string strx = x.ToString();
MessageBox.Show("double from int – " + y1.ToString() + "\r\nint from double – " + x1.ToString() + "\r\nstring from int – " + strx);
And when we press the button we see that integer x has been cast to a double. Double y has been cast to an int and int x has then been cast to a string. Notice the fact that when you cast the double to a string only the whole numbers were included, the decimal values were lost.
There are also built-in type cast functions that are available in C#.NET
||Converts a type to a Boolean value, where possible
||Converts a type to a byte
||Converts a type to a single Unicode character
||Converts a type (integer or string type) to date-time structures
||Converts a floating point or integer type to a decimal type
||Converts a type to a double type
||Converts a type to a 16-bit integer
||Converts a type to a 32-bit integer
||Converts a type to a 64-bit integer
||Converts a type to a signed byte type
||Converts a type to a small floating point number
||Converts a type to a string
||Converts a type to an unsigned int type
||Converts a type to an unsigned long type
||Converts a type to an unsigned big type
To use any of there you would instantiate and initialise a data type then press dot and choose the appropriate conversion function, example:
int d = 8;
string strd = d.ToString();
And now d has been cast to string strd.
A quick little note about type casting. If you attempt to cast an object into something that wont work, for example: a decimal into a bool then an error will be thrown and the code will stop, in this instance you can use a Try-Catch block to control what your application does when the error occurs, we will go over this in a later tutorial so don’t worry about it just now.
So, I think that is all I would like to say about type casting. In my next tutorial we will have a look at the various operators that are available to use in C# so until then, enjoy.