Changes

Jump to: navigation, search

C Sharp Variables and Constants

2,206 bytes added, 20:02, 11 January 2008
C# String Variables
In the preceding section we looked at storing individual characters in a ''char'' variable. Whilst this works for storing a single letter or number it is of little use for storing entire words or sentences. For this purpose the ''string'' variable type is supported by C#. Variables of type ''string'' can store a string of any number of characters.
 
String values are surrounded by double quotes ("). For example:
 
<pre>
string myString = "This is a string";
</pre>
 
A string declaration in C# cannot be spread over multiple lines. If a string needs to be split over multiple lines by new lines the ''\n'' special character can be used. For example:
 
<pre>
string myString = "This is line one\nThis is line two\nThis is line 3";
 
System.Console.WriteLine (myString);
</pre>
 
The above example code will result in the following output:
 
<pre>
This is line one
This is line two
</pre>
 
== Casting Variable Types in C# ==
 
In instances where it is safe to do so without data loss C# will allow you to assign a value from one type of variable to another simply using the assignment operator. For example, since a ''long'' variable is quite capable of storing any value that can be stored in an ''int'' variable an assignment such as the following is perfectly valid:
 
<pre>
int myInteger = 20;
long myLong;
 
myLong = myInteger;
</pre>
 
The same is not true of assigning a ''long'' to an ''int'' since a long is capable of storing significantly larger numbers than an ''int'' (an ''int'' is 4 bytes long versus 8 bytes for a ''long''). Attempting to squeeze a ''long'' into an ''int'' value would inevitably result in lost data. For this reason the C# compiler will flag such an attempt as an error and stubbornly refuse to compile the code.
 
it is just possible however, that you as the programmer, know that even though a variable is a ''long'' type that it will never contain a value greater than an ''int'' is capable of storing. In this case you might legitimately want to assign the value stored in a ''long'' variable to an ''int'' variable. This can be achieved by using a cast to convert the long value.
 
Casts are performed by placing the variable type to which you wish to convert before the name of the variable you wish to convert from. For example, to convert a ''long'' value to an ''int'' during an assignment operation:
 
<pre>
int myInteger;
long myLong = 1232;
 
myInteger = (int)myLong;
</pre>
 
Note that casting is only possible on numerical data types. It is not, therefore, possible to perform casts on ''string'', or ''bool'' variables.

Navigation menu