Home > Sample chapters > Programming > C#

Working with Variables, Operators, and Expressions in Microsoft Visual C#

Working with Primitive Data Types

C# has a number of built-in types called primitive data types. The following table lists the most commonly used primitive data types in C# and the range of values that you can store in each.

Data type

Description

Size (bits)

Range

Sample usage

int

Whole numbers (integers)

32

–231 through 231 – 1

int count;

count = 42;

long

Whole numbers (bigger range)

64

–263 through 263 – 1

long wait;

wait = 42L;

float

Floating-point numbers

32

±1.5 x 10-45 through ±3.4 x 1038

float away;

away = 0.42F;

double

Double-precision (more accurate) floating-point numbers

64

±5.0 x 10-324 through ±1.7 x 10308

double trouble;

trouble = 0.42;

decimal

Monetary values

128

28 significant figures

decimal coin;

coin = 0.42M;

string

Sequence of characters

16 bits per character

Not applicable

string vest;

vest = “fortytwo”;

char

Single character

16

0 through 216 – 1

char grill;

grill = ‘x’;

bool

Boolean

8

true or false

bool teeth;

teeth = false;

Unassigned Local Variables

When you declare a variable, it contains a random value until you assign a value to it. This behavior was a rich source of bugs in C and C++ programs that created a variable and accidentally used it as a source of information before giving it a value. C# does not allow you to use an unassigned variable. You must assign a value to a variable before you can use it, otherwise your program will not compile. This requirement is called the definite assignment rule. For example, the following statements generate the compile-time error message “Use of unassigned local variable ‘age’” because the Console.WriteLine statement attempts to display the value of an uninitialized variable:

int age;
Console.WriteLine(age); // compile-time error

Displaying Primitive Data Type Values

In the following exercise, you use a C# program named PrimitiveDataTypes to demonstrate how several primitive data types work.

Display primitive data type values

  1. Start Visual Studio 2012 if it is not already running.

  2. On the FILE menu, point to Open, and then click Project/Solution.

    The Open Project dialog box appears.

  3. If you are using Windows 8, move to the \Microsoft Press\Visual CSharp Step By Step\Chapter 2\Windows 8\PrimitiveDataTypes folder in your Documents folder. If you are using Windows 7, move to the \Microsoft Press\Visual CSharp Step By Step\Chapter 2\Windows 7\PrimitiveDataTypes folder in your Documents folder.

  4. Select the PrimitiveDataTypes solution file, and then click Open.

    The solution loads, and Solution Explorer displays the PrimitiveDataTypes project.

  5. On the DEBUG menu, click Start Debugging.

    You might see some warnings in Visual Studio. You can safely ignore them. (You will correct them in the next exercise.)

    If you are using Windows 8, the following page is displayed:

    If you are using Windows 7, the following window appears:

    httpatomoreillycomsourcemspimages1681240.jpg
  6. In the Choose a Data Type list, click the string type.

    The value “forty two” appears in the Sample Value box.

  7. Click the int type in the list.

    The value “to do” appears in the Sample Value box, indicating that the statements to display an int value still need to be written.

  8. Click each data type in the list. Confirm that the code for the double and bool types is not yet implemented.

  9. Return to Visual Studio 2012, and on the DEBUG menu click Stop Debugging.

Use primitive data types in code

  1. In Solution Explorer, expand the PrimitiveDataTypes project (if it is not already expanded) and then double-click MainWindow.xaml.

    The form for the application appears in the Design View window.

  2. In the XAML pane, scroll down to locate the markup for the ListBox control. This control displays the list of data types in the left part of the form, and it looks like this (some of the properties have been removed from this text):

    <ListBox x:Name="type" ... SelectionChanged="typeSelectionChanged">
      <ListBoxItem>int</ListBoxItem>
      <ListBoxItem>long</ListBoxItem>
      <ListBoxItem>float</ListBoxItem>
      <ListBoxItem>double</ListBoxItem>
      <ListBoxItem>decimal</ListBoxItem>
      <ListBoxItem>string</ListBoxItem>
      <ListBoxItem>char</ListBoxItem>
      <ListBoxItem>bool</ListBoxItem>
    </ListBox>

    The ListBox control displays each data type as a separate ListBoxItem. When the application is running, if a user clicks an item in the list, the SelectionChanged event occurs (this is a little bit like the Clicked event that occurs when the user clicks a button, which you saw in Chapter 1). You can see that in this case, the ListBox invokes the typeSelectionChanged method. This method is defined in the MainWindow.xaml.cs file.

  3. On the VIEW menu, click Code.

    The Code and Text Editor window opens, displaying the MainWindow.xaml.cs file.

  4. In the Code and Text Editor window, find the typeSelectionChanged method.

    If you have programmed using another language, you can probably guess how the typeSelectionChanged method works; if not, then Chapter 4, “Using Decision Statements,” will make this code clear. At present, all you need to understand is that when the user clicks an item in the ListBox control, the value of the item is passed to this method, which then uses this value to determine what happens next. For example, if the user clicks the float value, then this method calls another method named showFloatValue.

  5. Scroll down through the code and find the showFloatValue method, which looks like this:

    private void showFloatValue()
    {
      float floatVar;
      floatVar = 0.42F;
      value.Text = floatVar.ToString();
    }

    The body of this method contains three statements. The first statement declares a variable named floatVar of type float.

    The second statement assigns floatVar the value 0.42F. (The F is a type suffix specifying that 0.42 should be treated as a float value. If you forget the F, the value 0.42 is treated as a double and your program will not compile, because you cannot assign a value of one type to a variable of a different type without writing additional code—C# is very strict in this respect.)

    The third statement displays the value of this variable in the value text box on the form. This statement requires your attention. If you remember from Chapter 1, the way in which you display an item in a text box is to set its Text property (you did this by using XAML in Chapter 1). You can also perform this task programmatically, which is what is going on here. Notice that you access the property of an object by using the same dot notation that you saw for running a method. (Remember Console.WriteLine from Chapter 1?) Also, the data that you put in the Text property must be a string and not a number. If you try to assign a number to the Text property, your program will not compile. Fortunately, the .NET Framework provides some help in the form of the ToString method.

    Every data type in the .NET Framework has a ToString method. The purpose of ToString is to convert an object to its string representation. The showFloatValue method uses the ToString method of the float variable floatVar object to generate a string version of the value of this variable. This string can then be safely assigned to the Text property of the value text box. When you create your own data types and classes, you can define your own implementation of the ToString method to specify how your class should be represented as a string. You learn more about creating your own classes in Chapter 7, “Creating and Managing Classes and Objects.”

  6. In the Code and Text Editor window, locate the showIntValue method:

    private void showIntValue()
    {
        value.Text = "to do";
    }

    The showIntValue method is called when you click the int type in the list box.

  7. Type the following two statements at the start of the showIntValue method, on a new line after the opening brace, as shown in bold type in the following code:

    private void showIntValue()
    {
        int intVar;
        intVar = 42;
        value.Text = "to do";
    }

    The first statement creates a variable called intVar that can hold an int value. The second statement assigns the value 42 to this variable.

  8. In the original statement in this method, change the string “to do” to intVar.ToString().

    The method should now look exactly like this:

    private void showIntValue()
    {
        int intVar;
        intVar = 42;
        value.Text = intVar.ToString();
    }
  9. On the DEBUG menu, click Start Debugging.

    The form appears again.

  10. Select the int type in the Choose a Data Type list. Confirm that the value 42 is displayed in the Sample Value text box.

  11. Return to Visual Studio, and on the DEBUG menu click Stop Debugging.

  12. In the Code and Text Editor window, find the showDoubleValue method.

  13. Edit the showDoubleValue method exactly as shown in bold type in the following code:

    private void showDoubleValue()
    {
        double doubleVar;
        doubleVar = 0.42;
        value.Text = doubleVar.ToString();
    }

    This code is similar to the showIntValue method, except that it creates a variable called doubleVar that holds double values, and it is assigned the value 0.42.

  14. In the Code and Text Editor window, locate the showBoolValue method.

  15. Edit the showBoolValue method exactly as follows:

    private void showBoolValue()
    {
        bool boolVar;
        boolVar = false;
        value.Text = boolVar.ToString();
    }

    Again, this code is similar to the previous examples, except that boolVar can only hold a Boolean value, true or false.

  16. On the DEBUG menu, click Start Debugging.

  17. In the Choose a Data Type list, select the int, double, and bool types. In each case, verify that the correct value is displayed in the Sample Value text box.

  18. Return to Visual Studio, and on the DEBUG menu click Stop Debugging.