CSCI 1301

Data Types

1. Learning Objectives

  • Identify (some) common data types in C#
  • How to choose which type to use in a program

2. Data Types in C#

There are several different types in C#, but here are the common ones we will use:

charsingle character'a', '9', '*'
stringtext values"Hello", "Bye"
boolBoolean type, either true or falsetrue, false
intwhole numbers, 32-bit range5, 23870, -891
longwhole number, 64-bit range23483284799
floatdecimal number with ~ 7-8 digit precision5.4f, -2.3F
doubledecimal number with ~ 15-16 digit precision-8.94d, 123.9D
decimaldecimal numbers needing high precision e.g. currency89.99M, 5.99m

int and long types listed above can be used to store both negative and positive values because they are signed. unsigned versions of these types also exist. Unsigned types cannot store negative values.

The choice of data type defines what range of values that can be stored at the variable. For exact ranges review this document and official docs for built-in types.

3. C# Syntax for Data Types

char values are wrapped in single quotes

1Console.WriteLine('A'); // A is a char

string values are wrapped in double quotes

1Console.WriteLine("Hi there!"); // this is string type

bool values can only be true or false

1Console.WriteLine(true); // outputs: True
2Console.WriteLine(false); // outputs: False

int and long values are written as digits only (no quotes, punctuation, etc.)

1Console.WriteLine(12); // this is an int
2Console.WriteLine(9223372036854775807); // this is a long

float type values have postfix f or F

1Console.WriteLine(-4.5f); // negative float
2Console.WriteLine(6422F); // positive float

double type values have postfix d or D

When d or D is omitted, numeric value with decimals places is assumed to be a double

1Console.WriteLine(-12.283d); // negative double
2Console.WriteLine(667D); // positive double
3Console.WriteLine(667.23); // omitted type; evaluated as double

decimal type values have postfix m or M

1Console.WriteLine(-123M); // negative decimal
2Console.WriteLine(8.99m); // positive decimal

4. Exercise: Choose Data Types

Referring to the data types introduced above, what data type would you choose to represent these values in a program:

  1. User's name - examples: Jonny, Admin, user123
  2. Company street address - examples: 123 Main street, 45 Elm Street
  3. Current outside temperature
  4. Price for 1 gallon of milk
  5. Notification enabled (on/off)
  6. Email message body

Write your answers down then compare to this solution to check your understanding.

5. Summary

Identify (some) common data types in C#

The data types we will see frequently are string, char, int, long, float, double, decimal, and bool

How to choose which type to use in a program

Each data type has a specified range of values it can store. Data type selection is based on finding the most appropriate type for storing these expected values.