During the last article of this series we had a look on our first C#.Net code. And I hope it would have given you some confidence to start coding with C#.NET. You saw how easy it was to get into terms with the coding patterns in C#.NET. The .NET framework had made the task of the developer very much easier. Hence you’ll start to enjoy programming with C#.NET. In this article we’ll dive deeper into the world of C#.
In this article we would try to get into terms with variables in C# and we’ll see what the available variable types are in C#. In our last lesson we used some variables in our sample programs. Since it wasn’t the best time I didn’t try put too much attention into it. Now I think by now you have tried out some experiments by yourself with C#, and you are ready to move into some very important aspects not only in C#.NET, but also in most other programming languages as well.
Before talking about C# variables let’s consider about variables in a more generic perspective. Seriously,
- What are variables..?
- Why are they so important?
Here are the answers for those questions. Variables are temporary memory locations in the computer. They help to store values in the computer. In programming it is very useful to store values in this manner. So as a programmer you need to have a good understanding about the variable types in a particular programming language.
In other words, Variables represent storage locations. Every variable has a type that determines what values can be stored in the variable. C# is a type-safe language, and the C# compiler guarantees that values stored in variables are always of the appropriate type. Variables can hold either value types or reference types, or they can be pointers. Variable could be of two types Value types and Reference types.
A variable ‘x’ contains a value type; it directly contains an object with some value. No other variable ‘x’ can directly contain the object contained by ‘x’.
A variable ‘x’ contains a reference type, what it directly contains is something which refers to an object. Another variable ‘x’ can contain a reference to the same object referred to by ‘x’.
There are number of variable types in C#.NET. Each type is used in different occasions to represent different values and the amount one can store would differ from one type to another.
Figure 1: Some Variable Types in C#
As you can one type of data can be categorized into several sub types and after that they are considered as separate data types. The categorization is based on the amount of data that one variable could contain.
Ex: Type ‘Integer’ has sub categories based on its storage capacity. (ushort, uint, ulong, etc..)
A variable can be compared to a storage room, and is essential for the programmer. In C#, a variable is declared like this:
<data type> <name>;
an example could look like this:
that’s the most basic version. Usually, you wish to assign a visibility to the variable, and perhaps assign a value to it at the same time. It can be done like this:
<visibility> <data type> <name> = <value>;
An example could look like this:
private string name = “Saman”
We’ll discuss about access modifiers and encapsulation in the next lesson.
Let’s have a look at a simple example which uses variables.
Figure 2: Using Variables in C#.NET
P.N: The System imports of this example are removed from this example.
In our last article we experimented on Graphical User Interface elements like Forms and Text Fields, so this time we’ll have look at C# consoles.
Let’s have a closer look at that example,
As you can see too variables called ‘name’ and ‘address’ are declared at the top. If you want you can assign ‘null’ to each of them. When you are doing large programs that is a very god practice to have. Furthermore I have commented what I am doing in the code that too is a very good practice to have when coding. It will not only help some other person who is reading the code, but later on you too might get benefited from it.
“Console.ReadLine();” will assign the user entered value to the variables we declared.
“Console.WriteLine(“You are ” + name + “, ” + “from ” + address);”
Would display that result on the on the Console screen,
Figure 3: Output through the console window.
“(“You are ” + name + “, ” + “from ” + address);”
Here you’ll notice that string we entered and string values in variables are combined through a ‘+’ sign. This is called string concatenation. This is a very useful technique to know, one that will be very useful in programming. We’ll be going lot of concetanation related things in this series.
Earlier we talked about two variable types in value type and referance type, let’s have a look what reference type is.
The pre-defined reference types are object and string, where Object is the ultimate base class of all other types. New reference types can be defined using ‘class’, ‘interface’, and ‘delegate’ declarations.
Reference types actually hold the value of a memory address occupied by the object they reference. Consider the following piece of code, in which two variables are given a reference to the same object (for the sake of the example, this object is taken to contain the numeric property ‘myValue’).
Object name = new Object ();
x.myValue = 10;
object y = x;
y.myValue = 20;
After this both x and y would be equal to ‘20’.
Let’s consider about a string for reference types now,
string name = “saman”
string name1 = name;
name = “nadun”
What happens is that a new string object is created for ‘name1’ to point to. Hence, following this piece of code, name equals “nadun”, whereas s2 still equals “saman”.
The reason for this behavior is that string objects are ‘immutable’. That is, the properties of these objects can’t themselves change. So in order to change what a string variable references, a new string object must be created.
Before wrapping up this article for this edition, will have another example, this time using type casting as well,
Type casting is a technique where one variable type is converted to another; this can’t be done every time. And at times could result in loss of data as well.
Ex: when converting a ‘float’ to an ‘int’, floats floating point value may get lost and we might lose some data I the process.
Hence have to be very precise when doing type casting. But this too is a very important practice when it comes to programming.
Figure 4: Sample Code on type casting
In here you will see the usual variable declaration, after that you need to convert textbox values to whatever type you need to assign it to. By default all the textbox values are as strings. So here I had converted text box values into type ‘int’ and ‘float’. There are C# in- built methods for this work;
Ex: age = int.Parse(textBox2.Text);
salary = float.Parse(textBox3.Text);
In the next line I have done an explicit type cast. It is very simple to do it. You have to give the type you want it to become in a parenthesis and assign it to similar type of a variable you want. Here ‘salary’ is in float and it is assigned to an ‘int’.
Ex: int salary_to = (int)salary;
After tht these results are displayed in a Message box. The result is as follows.
Figure 5: Form for the example and the Final Output
This shows some drawback of type casting, after the type cast Value ‘salary’ has lost his floating point values. So have to be very precise in doing this operation.
That’s it for this edition on C#.NET. In our next edition we’ll have look at access modifiers, encapsulation and few other concepts. Till then enjoy and have a nice time..!
For more on Data types you can visit: