Data Type is a basic classification which identifies different types of data.Data Types helps in:Determining the possible values of a variablePossible operations which can be executed on the typeMeaning of the dataDifferent ways to store the data
Data Types are of different types:
Primitive data Types
Composite Data Types
*
Primitive data types are those data types which are not defined in terms of other data types.
Examples are:
Integer
Floating Point
Boolean
Character
*
NOTE: primitive here is not the same as how we use it when referring to the primitive types in Java even though they are mostly the same types. By primitive, we mean directly supported by hardware. Strings do not appear in this list because strings are rarely supported directly in hardware, instead they are stored as individual characters and linked together through some mechanism implemented by the programming language (usually as arrays of characters).
What about pointer types? You’ll notice that they do not appear above. Typically, pointers are just unsigned int values. But we treat pointers differently than ints because we do not permit pointer arithmetic (except in a few languages) and require dereferencing of some kind. Dereferencing may be directly supported in hardware by having indirect addressing modes.
Integers are used to hold integer values only.This is further categorized into:
byte
short
int
long
signed
Unsigned
Examples are:
unsigned int x = 21234;
unsigned int y = 31234;
unsigned int z;
z = x + y;
This data type contains decimal points.Examples are:
float f = 20.0 / 3.0;
Current standard version of floating-point
Single-precision (float)
One word: 1 sign bit, 23 bit fraction, 8 bit exponent
Positive range: 1.17549435 × 10-38 … 3.40282347 × 10+38
Double-precision (double)
Two words: 1 sign bit, 52 bit fraction, 11 bit exponent
Positive range: 2.2250738585072014 × 10-308 … 1.7976931348623157 × 10+308
*
Boolean Data type is used to store logical value.It can have either True or False value.It is a one bit representation0 represents false value1 represents true valueExample: Boolean a;
a=true;
Roman alphabet, punctuation, digits, and other symbols:Can encode within one byte (256 symbols)
In C:
char a_char = ’a’;
char newline_char = ’\n’;
char tab_char = ’\t’;
char backslash_char = ’\\’;
These data types are derived from more than one primitive data type.Examples are:
Arrays
Records
Structure
Union
Arrays are a finite sequence of variables of the same data type These are commonly implemented by the compiler generating array descriptors for each array
here we have
descriptors for
1-D and multi-D
arrays
*
Records are Varied aggregate of data elementsThe elements of a record are known as fields or membersRecords were introduced in COBOLThis data type is used in many languages.In Java, the functionality of records are achieved through the use of classes
Examples:
COBOL (nested structure.
Data Type is a basic classification which identifies.docx
1. Data Type is a basic classification which identifies different
types of data.Data Types helps in:Determining the possible
values of a variablePossible operations which can be executed
on the typeMeaning of the dataDifferent ways to store the data
Data Types are of different types:
Primitive data Types
Composite Data Types
*
Primitive data types are those data types which are not defined
in terms of other data types.
Examples are:
Integer
Floating Point
Boolean
Character
*
NOTE: primitive here is not the same as how we use it when
referring to the primitive types in Java even though they are
2. mostly the same types. By primitive, we mean directly
supported by hardware. Strings do not appear in this list
because strings are rarely supported directly in hardware,
instead they are stored as individual characters and linked
together through some mechanism implemented by the
programming language (usually as arrays of characters).
What about pointer types? You’ll notice that they do not appear
above. Typically, pointers are just unsigned int values. But we
treat pointers differently than ints because we do not permit
pointer arithmetic (except in a few languages) and require
dereferencing of some kind. Dereferencing may be directly
supported in hardware by having indirect addressing modes.
Integers are used to hold integer values only.This is further
categorized into:
byte
short
int
long
signed
Unsigned
Examples are:
unsigned int x = 21234;
unsigned int y = 31234;
unsigned int z;
z = x + y;
This data type contains decimal points.Examples are:
3. float f = 20.0 / 3.0;
Current standard version of floating-point
Single-precision (float)
One word: 1 sign bit, 23 bit fraction, 8 bit exponent
Positive range: 1.17549435 × 10-38 … 3.40282347 × 10+38
Double-precision (double)
Two words: 1 sign bit, 52 bit fraction, 11 bit exponent
Positive range: 2.2250738585072014 × 10-308 …
1.7976931348623157 × 10+308
*
Boolean Data type is used to store logical value.It can have
either True or False value.It is a one bit representation0
represents false value1 represents true valueExample: Boolean
a;
a=true;
Roman alphabet, punctuation, digits, and other symbols:Can
encode within one byte (256 symbols)
In C:
char a_char = ’a’;
char newline_char = ’n’;
char tab_char = ’t’;
char backslash_char = ’’;
These data types are derived from more than one primitive data
type.Examples are:
Arrays
4. Records
Structure
Union
Arrays are a finite sequence of variables of the same data type
These are commonly implemented by the compiler generating
array descriptors for each array
here we have
descriptors for
1-D and multi-D
arrays
*
Records are Varied aggregate of data elementsThe elements of a
record are known as fields or membersRecords were introduced
in COBOLThis data type is used in many languages.In Java, the
functionality of records are achieved through the use of classes
Examples:
COBOL (nested structure in one definition)
01 EMPLOYEE-RECORD.
02 EMPLOYEE-NAME.
05 FIRST PICTURE IS X(10).
05 MIDDLE PICTURE IS X(10).
05 LAST PICTURE IS X(20).
02 HOURLY-RATE PICTURE IS 99V99.
*
5. Types which can store different types of variables at different
times of execution at the same memory location.Example:
Integer X Real Y
Equivalence (X, Y)
declares one memory location for both X and Y
the Equivalence statement is not a type, it just commands the
compiler to share the same memory locationOther languages
have union typesthe type defines same or common location for
two variables of different types
*
The rationale for Union types is twofold, neither of which is
particularly relevant today:To save memory space by reusing a
memory location that had been allocated for a different
variable. In this way, the same memory location might serve
for multiple subroutines. Since today we have plenty of
memory, and most languages use the run-time stack or heap for
local subroutine variables, sharing of memory locations is no
longer required or desirable.To provide the programmer with
flexibility in that a given memory location can be used for
multiple types. For instance, this allows a programmer to get
around type checking by storing (as an example) an int value
but later interpreting it as a float. This is dangerous but
programmers may find this useful in very rare cases.
Used for indirect addressing for dynamic memorydynamic
memory when allocated, does not have a name, so these are
unnamed or anonymous variables and can only be accessed
through a pointerPointers store memory locations or nullusually
null is a special value so that pointers can be implemented as
special types of int valuesBy making pointers a specific type,
some static allocation is possible the pointer itself can be
6. allocated at compile-time, and uses of the pointer can be type
checked at compile-time
int *, float *, char * – used to denote a pointer type, which is a
memory address type
*
Pointer scope and lifetime will probably be the same as any
variable’s scope and lifetime – that is, this decision covers all
types of variables, not just pointers
The lifetime of what is being pointed to is different, this is
almost always a dynamic situation, allocated at run-time upon
request (whether explicitly or implicitly as in Lisp or Perl).
The lifetime ends when the item is deallocated. This is explicit
in many languages, but implicit in languages with a garbage
collector – its lifetime ends when nothing points at it. Notice
that the garbage collector may or may not retrieve that memory
location immediately, so it still may be allocated, but
inaccessible.
Data Types
7. Introduction
Booleans
Examples are:
x AND y - returns True if both x and y are true; returns False if
either x or y are false.
x OR y - returns True if either x or y, or both x and y are true;
returns False only if x and y are both false.
x XOR y - returns True if only x or y is true; returns False if x
and y are both true or both false.
NOT x - returns True if x is false (or null); returns False if x is
true.
Characters
8. Examples are:
A, 1, +, ! & #
Floating points
Examples are:
The numbers 5.5, 0.001, and -2,345.6789 are floating point
numbers.
integers
9. Examples are:
The numbers 10, 0, -25, and 5,148 are all integers.
arrays
Examples are:
arrayname[0] = "This ";
arrayname[1] = "is ";
arrayname[2] = "pretty simple.";
print arrayname[0];
print arrayname[1];
print arrayname[2];
Strings
10. Examples are:
using System; class Strings { static void Main() { string word =
"ZetCode"; char c = word[0]; Console.WriteLine(c); } }
Record types
Examples are:
Supported COBOL Data Types
COMP-1
A 4-byte, single precision, floating-point Real data type that
specifies internal floating-point items. The sign is contained in
the first bit of the leftmost byte, and the exponent is contained
in the remaining seven bits of that byte. The remaining three
bytes hold the mantissa.
COMP-2
11. An 8-byte, double precision, floating-point Real data type that
specifies internal floating-point items. The sign is contained in
the first bit of the leftmost byte, and the exponent is contained
in the remaining seven bits of the first byte. The remaining
seven bytes hold the mantissa.
conclusion
Home Contents
C# data types
In this part of the C# tutorial, we will talk about data types.
Computer programs work with data. Spreadsheets, text editors,
calculators or chat clients. Tools
to work with various data types are essential part of a modern
computer language. A data type is
a set of values and the allowable operations on those values.
The two fundamental data types in C# are value types and
reference types. Primitive types (except
12. strings), enumerations, and structures are value types. Classes,
strings, interfaces, arrays, and
delegates are reference types. Every type has a default value.
Reference types are created on the
Heap. The lifetime of the reference type is managed by the
.NET framework. The default value for
reference types is null reference. Assignment to a variable of a
reference type creates a copy of the
reference rather than a copy of the referenced value. Value
types are created on the stack. The
lifetime is determined by the lifetime of the variable.
Assignment to a variable of a value type
creates a copy of the value being assigned. Value types have
different default values. For example,
boolean default value is false, decimal 0, string an empty string
"".
Boolean values
There is a duality built in our world. There is a Heaven and
Earth, water and fire, jing and jang,
man and woman, love and hatred. In C# the bool data type is a
primitive data type having one of
two values: true or false. This is a fundamental data type that is
very common in computer
programs.
13. Happy parents are waiting a child to be born. They have chosen
a name for both possibilities. If it
is going to be a boy, they have chosen John. If it is going to be
a girl, they have chosen Victoria.
using System;
class BooleanType
{
static void Main()
{
bool male = false;
Random random = new Random();
male = Convert.ToBoolean(random.Next(0, 2));
if (male)
{
Console.WriteLine("We will use name John");
} else
{
Console.WriteLine("We will use name Victoria");
}
14. }
}
Page 1 of 14C# data types
3/18/2014http://zetcode.com/lang/csharp/datatypes/
The program uses a random number generator to simulate our
case.
bool male = false;
The male variable is our boolean variable, initiated at first to
false.
Random random = new Random();
We create a Random object which is used to compute random
numbers. It is part of the System
namespace.
male = Convert.ToBoolean(random.Next(0, 2));
The Next() method returns a random number within a specified
range. The lower bound is
included, the upper bound is not. In other words, we receive
either 0, or 1. Later the Convert()
method converts these values to boolean ones, 0 to false, 1 to
true.
15. if (male)
{
Console.WriteLine("We will use name John");
} else
{
Console.WriteLine("We will use name Victoria");
}
If the male variable is set to true, we choose the name John.
Otherwise, we choose the name
Victoria. Control structures like if/else statements work with
boolean values.
$ ./booleantype.exe
We will use name John
$ ./booleantype.exe
We will use name Victoria
$ ./booleantype.exe
We will use name Victoria
$ ./booleantype.exe
We will use name John
16. Running the program several times gives this output.
Integers
Integers are a subset of the real numbers. They are written
without a fraction or a decimal
component. Integers fall within a set Z = {..., -2, -1, 0, 1, 2, ...}.
Integers are infinite.
In computer languages, integers are primitive data types.
Computers can practically work only
with a subset of integer values, because computers have finite
capacity. Integers are used to count
discrete entities. We can have 3, 4, 6 humans, but we cannot
have 3.33 humans. We can have 3.33
kilograms.
V B A l i a s . N E T T y p e Si ze R a n g e
sbyte System.SByte 1 byte -128 to 127
byte System.Byte 1 byte 0 to 255
short System.Int16 2 bytes -32,768 to 32,767
ushort System.UInt16 2 bytes 0 to 65,535
int System.Int32 4 bytes -2,147,483,648 to 2,147,483,647
uint System.UInt32 4 bytes 0 to 4,294,967,295
17. long System.Int64 8 bytes -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
ulong System.UInt64 8 bytes 0 to 18,446,744,073,709,551,615
These integer types may be used according to our needs. No
one, (except perhaps for some
biblical people), can be older than 120, 130 years. We can then
use the byte type for age variable
in a program. This will save some memory.
Page 2 of 14C# data types
3/18/2014http://zetcode.com/lang/csharp/datatypes/
using System;
class Overflow
{
static void Main()
{
byte a = 254;
Console.WriteLine(a);
a++;
Console.WriteLine(a);
18. a++;
Console.WriteLine(a);
a++;
Console.WriteLine(a);
}
}
In this example, we try to assign a value beyond the range of a
data type. This leads to an
arithmetic overflow. An arithmetic overflow is a condition that
occurs when a calculation
produces a result that is greater in magnitude than that which a
given register or storage location
can store or represent.
$ ./overflow.exe
254
255
0
1
In C#, when an overflow occurs, the variable is reset to the
lower bound of the data type. (In case
19. of a byte type it is zero.) In contrast, Visual Basic would throw
an exception.
Integers can be specified in two different notations in C#:
decimal and hexadecimal. There are no
notations for octal or binary values. Decimal numbers are used
normally as we know them.
Hexadecimal numbers are preceded with 0x characters.
using System;
class Notations
{
static void Main()
{
int num1 = 31;
int num2 = 0x31;
Console.WriteLine(num1);
Console.WriteLine(num2);
}
}
We assign 31 to two variables using two different notations.
And we print them to the console.
20. $ ./intnotations.exe
31
49
The default notation is the decimal. The program shows these
two numbers in decimal. In other
words, hexadecimal 0x31 is 49 decimal.
If we work with integers, we deal with discrete entities. We
would use integers to count apples.
using System;
public class Apples
{
Page 3 of 14C# data types
3/18/2014http://zetcode.com/lang/csharp/datatypes/
static void Main()
{
int baskets = 16;
int applesInBasket = 24;
int total = baskets * applesInBasket;
21. Console.WriteLine("There are total of {0} apples", total);
}
}
In our program, we count the total amount of apples. We use the
multiplication operation.
int baskets = 16;
int applesInBasket = 24;
The number of baskets and the number of apples in each basket
are integer values.
int total = baskets * applesInBasket;
Multiplying those values we get an integer too.
$ ./apples.exe
There are total of 384 apples
This is the output of the program.
Floating point numbers
Floating point numbers represent real numbers in computing.
Real numbers measure continuous
quantities, like weight, height or speed. In C# we have three
floating point types: float, double and
decimal.
22. C # A l i a s . N E T T y p e S i z e P re c i s i o n R a ng e
float System.Single 4 bytes 7 digits 1.5 x 10
-45
to 3.4 x 10
38
double System.Double 8 bytes 15-16 digits 5.0 x 10
-324
to 1.7 x 10
308
decimal System.Decimal 16 bytes 28-29 decimal places 1.0 x 10
-28
to 7.9 x 10
28
The above table gives the characteristics of the floating point
types.
By default, real numbers are double in C# programs. To use a
different type, we must use a suffix.
The F/f for float numbers and M/m for decimal numbers.
using System;
class Floats
{
static void Main()
23. {
float n1 = 1.234f;
double n2 = 1.234;
decimal n3 = 1.234m;
Console.WriteLine(n1);
Console.WriteLine(n2);
Console.WriteLine(n3);
Console.WriteLine(n1.GetType());
Console.WriteLine(n2.GetType());
Console.WriteLine(n3.GetType());
}
}
In the above program, we use three different literal notations for
floating point numbers.
Page 4 of 14C# data types
3/18/2014http://zetcode.com/lang/csharp/datatypes/
float n1 = 1.234f;
24. The f suffix is used for a float number.
double n2 = 1.234;
If we do not use a suffix, then it is a double number.
Console.WriteLine(n1.GetType());
The GetType() method returns the type of the number.
$ ./floats.exe
1.234
1.234
1.234
System.Single
System.Double
System.Decimal
This is the output.
We can use various syntax to create floating point values.
using System;
class Notations
{
static void Main()
25. {
float n1 = 1.234f;
float n2 = 1.2e-3f;
float n3 = (float) 1 / 3;
Console.WriteLine(n1);
Console.WriteLine(n2);
Console.WriteLine(n3);
}
}
We have three ways to create floating point values. The first is
the 'normal' way using a decimal
point. The second uses a scientific notation. And the last one as
a result of a numerical operation.
float n2 = 1.2e-3f;
This is the scientific notation for floating point numbers. Also
known as exponential notation, it is
a way of writing numbers too large or small to be conveniently
written in standard decimal
notation.
float n3 = (float) 1 / 3;
26. The (float) construct is called casting. The division operation
returns integer numbers by
default. By casting we get a float number.
$ ./fnotations.exe
1.234
0.0012
0.3333333
This is the output of the above program.
The float and double types are inexact.
using System;
Page 5 of 14C# data types
3/18/2014http://zetcode.com/lang/csharp/datatypes/
class CSharpApp
{
static void Main()
{
float n1 = (float) 1 / 3;
double n2 = (double) 1 / 3;
27. if (n1 == n2)
{
Console.WriteLine("Numbers are equal");
} else {
Console.WriteLine("Numbers are not equal");
}
}
}
The float and double values are stored with different precision.
Caution should be exercised
when comparing floating point values.
$ ./fequal.exe
Numbers are not equal
And the numbers are not equal.
Let's say a sprinter for 100m ran 9.87s. What is his speed in
km/h?
using System;
class Sprinter
{
28. static void Main()
{
float distance;
float time;
float speed;
distance = 0.1f;
time = 9.87f / 3600;
speed = distance / time;
Console.WriteLine("The average speed of a sprinter is {0}
km/h", speed);
}
}
In this example, it is necessary to use floating point values.
distance = 0.1f;
100m is 0.1 km.
time = 9.87f / 3600;
9.87s is 9.87/60*60 h.
speed = distance / time;
29. To get the speed, we divide the distance by the time.
$ ./sprinter.exe
The average speed of a sprinter is 36.47416 km/h
This is the output of the sprinter.exe program.
Page 6 of 14C# data types
3/18/2014http://zetcode.com/lang/csharp/datatypes/
Enumerations
Enumerated type (also called enumeration or enum) is a data
type consisting of a set of named
values. A variable that has been declared as having an
enumerated type can be assigned any of the
enumerators as a value. Enumerations make the code more
readable.
using System;
class Enumerations
{
enum Days
{
Monday,
31. }
In our code example, we create an enumeration for week days.
enum Days
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
The enumeration is created with a enum keyword. The Monday,
Tuesday ... barewords store in
fact numbers 0..6.
Days day = Days.Monday;
We have a variable called day which is of the enumerated type
Days. It is initialized to Monday.
if (day == Days.Monday)
32. {
Console.WriteLine("It is Monday");
}
This code is more readable than comparing a day variable to
some number.
Console.WriteLine(day);
Page 7 of 14C# data types
3/18/2014http://zetcode.com/lang/csharp/datatypes/
This line prints Monday to the console.
foreach(int i in Enum.GetValues(typeof(Days)))
Console.WriteLine(i);
This loop prints 0..6 to the console. We get underlying types of
the enum values. For a computer,
an enum is just a number. The typeof is an operator used to
obtain the System.Type object for a
type. It is needed by the GetValues() method. This method
returns an array of the values of a
specified enumeration. And the foreach keyword goes through
the array, element by element
33. and prints them to the terminal.
We further work with enumerations.
using System;
class Enumerations2
{
public enum Seasons : byte
{
Spring = 1,
Summer = 2,
Autumn = 3,
Winter = 4
}
static void Main()
{
Seasons s1 = Seasons.Spring;
Seasons s2 = Seasons.Autumn;
Console.WriteLine(s1);
Console.WriteLine(s2);
34. }
}
Seasons can be easily used as enums. We can specify the
underlying type for the enum and we can
give exact values for them.
public enum Seasons : byte
{
Spring = 1,
Summer = 2,
Autumn = 3,
Winter = 4
}
With a colon and a data type we specify the underlying type for
the enum. We also give each
member a specific number.
Console.WriteLine(s1);
Console.WriteLine(s2);
These two lines print the enum values to the console.
$ ./seasons.exe
35. Spring
Autumn
This is the output of the seasons.exe program.
Strings and chars
Page 8 of 14C# data types
3/18/2014http://zetcode.com/lang/csharp/datatypes/
The string is a data type representing textual data in computer
programs. A string in C# is a
sequence of unicode characters. A char is a single unicode
character. Strings are enclosed by
double quotes.
Since strings are very important in every programming
language, we will dedicate a whole chapter
to them. Here we only present a small example.
using System;
class Strings
{
static void Main()
{
36. string word = "ZetCode";
char c = word[0];
Console.WriteLine(c);
}
}
The program prints 'Z' character to the terminal.
string word = "ZetCode";
Here we create a string variable and assign it the "ZetCode"
value.
char c = word[0];
A string is an array of unicode characters. We can use the array
access notation to get a specific
character from the string. The number inside the square brackets
is the index into the array of
characters. The index is counted from zero. It means that the
first character has index 0.
$ ./char.exe
Z
The program prints the first character of the "ZetCode" string to
the console.
37. Arrays
The array is a complex data type which handles a collection of
elements. Each of the elements can
be accessed by an index. All the elements of an array must be of
the same data type.
We dedicate a whole chapter to arrays; here we show only a
small example.
using System;
class ArrayExample
{
static void Main()
{
int[] numbers = new int[5];
numbers[0] = 3;
numbers[1] = 2;
numbers[2] = 1;
numbers[3] = 5;
numbers[4] = 6;
int len = numbers.Length;
for (int i=0; i<len; i++)
38. {
Console.WriteLine(numbers[i]);
}
Page 9 of 14C# data types
3/18/2014http://zetcode.com/lang/csharp/datatypes/
}
}
In this example, we declare an array, fill it with data and then
print the contents of the array to
the console.
int[] numbers = new int[5];
We declare an integer array which can store up to 5 integers. So
we have an array of five elements,
with indexes 0..4.
numbers[0] = 3;
numbers[1] = 2;
numbers[2] = 1;
numbers[3] = 5;
39. numbers[4] = 6;
Here we assign values to the created array. We can access the
elements of an array by the array
access notation. It consists of the array name followed by
square brackets. Inside the brackets we
specify the index to the element that we want.
int len = numbers.Length;
Each array has a Length property which returns the number of
elements in the array.
for (int i=0; i<len; i++)
{
Console.WriteLine(numbers[i]);
}
We traverse the array and print the data to the console.
DateTime
The DateTime is a value type. It represents an instant in time,
typically expressed as a date and
time of day.
using System;
class DateTimeExample
40. {
static void Main()
{
DateTime today;
today = DateTime.Now;
System.Console.WriteLine(today);
System.Console.WriteLine(today.ToShortDateString());
System.Console.WriteLine(today.ToShortTimeString());
}
}
We show today's date in three different formats: date & time,
date, and time.
DateTime today;
We declare a variable of DateTime data type.
today = DateTime.Now;
Gets a DateTime object that is set to the current date and time
on this computer, expressed as the
local time.
Page 10 of 14C# data types
41. 3/18/2014http://zetcode.com/lang/csharp/datatypes/
System.Console.WriteLine(today);
This line prints the date in full format.
System.Console.WriteLine(today.ToShortDateString());
System.Console.WriteLine(today.ToShortTimeString());
The ToShortDateString() returns a short date string format, the
ToShortTimeString()
returns a short time string format.
$ ./date.exe
10/15/2010 10:56:37 AM
10/15/2010
10:56 AM
We see the output of the example.
Type casting
We often work with multiple data types at once. Converting one
data type to another one is a
common job in programming. Type conversion or typecasting
refers to changing an entity of one
42. data type into another. There are two types of conversion:
implicit and explicit. Implicit type
conversion, also known as coercion, is an automatic type
conversion by the compiler.
using System;
class ImplicitTypeConversion
{
static void Main()
{
int val1 = 0;
byte val2 = 15;
val1 = val2;
Console.WriteLine(val1.GetType());
Console.WriteLine(val2.GetType());
Console.WriteLine(12 + 12.5);
Console.WriteLine("12" + 12);
}
}
In this example, we have several implicit conversions.
43. val1 = val2;
Here we work with two different types: int and byte. We assign
a byte value to an int value. It
is a widening operation. The int values have four bytes; byte
values have only one byte. Widening
conversions are allowed. If we wanted to assign a int to a byte,
this would be a shortening
conversion. Implicit shortening conversions are not allowed by
C# compiler. This is because in
implicit shortening conversion we could unintentionally loose
precision. We can do shortening
conversions, but we must inform the compiler about it. That we
know what we are doing. It can
be done with explicit conversion.
Console.WriteLine(12 + 12.5);
We add two values, one integer and one floating point value.
The result is a floating point value. It
is a widening implicit conversion.
Console.WriteLine("12" + 12);
The result is 1212. An integer is converted to a string and the
two strings are concatenated.
Page 11 of 14C# data types
44. 3/18/2014http://zetcode.com/lang/csharp/datatypes/
Next we will show some explicit conversions in C#.
using System;
class ExplicitTypeConversion
{
static void Main()
{
float a;
double b = 13.5;
int c;
a = (float) b;
c = (int) a;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
}
}
45. We have three values. We do some explicit conversions with
these values.
float a;
double b = 13.5;
int c;
We have a float value, a double value and an int value.
a = (float) b;
We convert a double value to a float value. Explicit conversion
is done by specifying the
intended type between two square brackets. In this case, no
precision is lost. 13.5 can be safely
assigned to both types.
c = (int) a;
We convert a float value to int value. In this statement, we
loose some precision. 13.5 becomes
13.
$ ./explicit.exe
13.5
13.5
13
46. We see the output of the explicit.exe program.
Nullable types
Value types cannot be assigned a null literal, reference types
can. Applications that work with
databases deal with the null value. Because of this, special
nullable types were introduced into the
C# language. Nullable types are instances of the
System.Nullable<T> struct.
using System;
class NullableType
{
static void Main()
{
Nullable<bool> male = null;
int? age = null;
Console.WriteLine(male.HasValue);
Console.WriteLine(age.HasValue);
Page 12 of 14C# data types
3/18/2014http://zetcode.com/lang/csharp/datatypes/
47. }
}
A simple example demonstrating nullable types.
Nullable<bool> male = null;
int? age = null;
There are two ways how to declare a nullable type. Either with
the Nullable<T> generic structure
in which the type is specified between the angle brackets. Or we
can use a question mark after the
type. The latter is in fact a shorthand for the first notation.
$ ./nullabletypes.exe
False
False
This is the output of the example.
Convert & Parse methods
There are two groups of methods which are used to convert
values.
using System;
class CSharpApp
52. creating true/false statements.
Boolean expressions use the operators AND, OR, XOR, and
NOT to compare values and return
a true or false result. These boolean operators are described in
the following four examples:
• X AND y - returns True if both x and y are true; returns False
if either x or y are false.
• X OR y - returns True if either x or y, or both x and y are true;
returns False only if x and
y are both false.
• X XOR y - returns True if only x or y is true; returns False if
x and y are both true or both
false.
• NOT X - returns True if x is false (or null); returns False if x
is true.
Since computers operate in binary (using only zeros and ones),
computer logic can often
expressed in boolean terms. For example, a true statement
returns a value of 1, while a false
statement returns a value of 0. Of course, most calculations
require more than a simple
true/false statement. Therefore, computer processors perform
complex calculations by
linking multiple binary (or boolean) statements together.
Complex boolean expressions can
be expressed as a series of logic gates.
Boolean expressions are also supported by most search engines.
When you enter keywords in
a search engine, you can refine your search using boolean
operators. For example, if you
want to look up information about the Apple iMac, but want
56. Array Definition - Printable Version Page 1 of 1
Array
An array is a data structure that contains a group of elements.
Typically these elements are all
of the same data type, such as an integer or string. Arrays are
commonly used in computer
programs to organize data so that a related set of values can be
easily sorted or searched.
For example, a search engine may use an array to store Web
pages found in a search
performed by the user. When displaying the results, the program
will output one element of
the array at a time. This may be done for a specified number of
values or until all the values
stored in the array have been output. While the program could
create a new variable for each
result found, storing the results in an array is much more
efficient way to manage memory.
The syntax for storing and displaying the values in an array
typically looks something like
this:
arrayname[0] = " T h i s ";
arrayname[1] = " i s ";
arrayname[2] = " p r e t t y s i m p l e . " ;
p r i n t a r r a y n a m e [ 0 ] ;
p r i n t a r r a y n a m e [ 1 ] ;
p r i n t a r r a y n a m e [ 2 ] ;
The above commands would print the first three values of the
array, or "This i s p r e t t y
59. operations. Such businesses have
a s m a l l staff o f professionals a n d can't always s u p p o r t
special needs, l i k e those o f
A d d i s o n a n d D r e w at GearUp. To o b t a i n the o n e - o
f - a - k i n d reports they need, A d d i s o n
a n d D r e w need to be creative and adaptable.
This chapter discusses the why, w h a t , and h o w of database
processing. We b e g i n
by describing the purpose of databases a n d t h e n explain the i
m p o r t a n t c o m p o n e n t s
of database systems, We t h e n overview the process of creating
a database system and
s u m m a r i z e y o u r role as a f u t u r e user o f such
systems.
Users have a crucial role in the development of database
applications. Specifically,
the s t r u c t u r e a n d c o n t e n t of the database depends e n
t i r e l y o n h o w users v i e w t h e i r
business a c t i v i t y To b u i l d the database, the developers v
n l l create a m o d e l of t h a t view
u s i n g a t o o l c a l l e d the e n t i t y - r e l a t i o n s h i p m
o d e l . You n e e d t o u n d e r s t a n d h o w to
i n t e r p r e t such models, because the d e v e l o p m e n t t e
a m m i g h t ask y o u to validate the
correctness of such a m o d e l w h e n b u i l d i n g a system
for y o u r use. Finally, we describe
the various database a d m i n i s t r a t i o n tasks.
T h i s c h a p t e r focuses o n database t e c h n o l o g y . Here
w e c o n s i d e r t h e basic
c o m p o n e n t s o f a database a n d t h e f u n c t i o n s of
database a p p l i c a t i o n s . You w i l l l e a r n
h o w A d d i s o n used database r e p o r t i n g to solve the
GearUp p r o b l e m i n Chapter 9.
60. ; What Is the Purpose of a Database?
The p u i p o s e of a database is t o keep track of things. W h e
n most students l e a r n that,
t h e y w o n d e r w h y we need a special t e c h n o l o g y for
such a s i m p l e task. W h y n o t just
use a list? I f the list is l o n g , p u t i t i n t o a spreadsheet.
I n fact, m a n y professionals do keep t r a c k of t h i n g s u s i
n g spreadsheets. I f the
structure of the list is simple enough, there is n o need to use
database technology. The
list of student grades i n Figure 5 - 1 , for example, w o r k s
perfectly w e l l i n a spreadsheet.
Suppose, however, t h a t the professor wants to track m o r e t
h a n j u s t grades. Say
t h a t the professor wants to record e m a i l messages as w e l l
. Or, perhaps the professor
wants to record b o t h e m a i l messages and office visits.
There is n o place i n Figure 5-1
t o r
shei
w o i
can
i n F i
is ea
aboL
h a s r
W e e
can
datal
61. A d a t
terms
As yoi
group.
A List of Student Grades,
Presented in a Spreadsheet
142
, •••5 • : => S SS
. ^ 1^ = » e 5 ? ' rJi;cr!l!!onslro:™::,r,c- j - t e - - - ^ ' iff i i
H'.V2 K V M F i n a l
e - - : e r -ii;sE,-. 1 ; . : ; 1M
4 FtiCHER f.1-y-!i 30L7 9 - 100 74
L-1- 5V',HE 1644 7e so 6-
I I E - J : - ! ! iTL-AFT 100 90 OS
- ROGERS il-ELL'-' mi 9S 100 95
Til.l .EFFREv ; 5 £ 5 100 8 ;
; V i - D E I n-F E 52c S SO 90 6 :
VERBEhR- AD-f.i iif ' 0 90 9 :
y m
Q2 What Is a Database? 143
Slu6ertN«tie J B 4 K E B . « I 0 R E A
62. SluJertNunbo |
HW1 I m
HW2 I Ten
MidTom j 78
EMAIL
Zs-i - tMi-s}i
OFFICE VISITS
.5;s - •I!:;e=
to record that a d d i t i o n a l data. Of course, the professor c o
u l d set up a separate spread-
sheet for e m a i l messages a n d another one for office visits, b
u t t h a t a w h v a r d s o l u t i o n
w o u l d be d i f f i c u l t to use because i t does n o t provide
all of the data i n one place.
Instead, the professor wants a f o r m like that i n Figure 5-2. W
i t h i t , the professor
can record s t u d e n t grades, emails, and office visits all i n
one place. A f o r m like the one
i n Figure 5-2 is d i f f i c u l t , i f n o t impossible, to p r o d u
c e f r o m a spreadsheet. Such a f o r m
is easily p r o d u c e d , however, f r o m a database.
The key d i s t i n c t i o n b e t w e e n Figures 5-1 a n d 5-2 is t
h a t the data i n Figure 5-1 is
about a single t h e m e or concept. It is about student grades o
n l y The data i n Figure 5-2
has m u l t i p l e themes; i t shows student grades, student
emails, and student office visits.
We can make a general rule from these examples: Lists o f data
i n v o l v i n g a single theme
can be stored i n a spreadsheet; lists that involve data w i t h m
63. u l t i p l e themes require a
database. We w i l l say more about this general rule as this
chapter proceeds.
Student Data Shown in a Form,
from a Database
As you will see, databases can
be more difficult to develop
than spreadsheets; this
difficulty causes some people
to prefer to luork with
spreadsheets—or at least
pretend to—as described in
the Guide on pages 166-167.
What Is a Database?
A database is a s e l f - d e s c r i b i n g c o l l e c t i o n of i n t
e g r a t e d records. To u n d e r s t a n d the
terms i n this d e f i n i t i o n , y o u first need to u n d e r s t a
n d the terms illustrated i n Figure 5-3.
As y o u l e a r n e d i n C h a p t e r 4, a byte is a character o f
data. I n databases, bytes are
grouped i n t o columns, such as Student Number and Student
Name. Columns are also
144 CHAPTER 5 Database Processing
Hierarchy of Data Elements Table or File rMiimhnr t t i i r i n n
t h h r
ittiirinntMiimhnr ttiiHnntMir j y m .
tiiHnntMiimhnr t t i i r i n n t h h m n Ukn I .
Student Number Student Name HW1 ... |
64. Group of
Records or Rows I Student Number Student Name H W l
Group of
Fields or Columns I Student Number 11 Student Name IE HWl
Group of
Bytes or Characters • [7] • • •
called fields. C o l u m n s or fields, i n t u r n , are g r o u p e d
i n t o rows, w h i c h aie also called
records. I n Figure 5-3, the collection of data for all c o l u m n
s {Student Number, Student
Name, HWl, HW2, a n d MidTerm) is called a row or a record.
Finally, a group of similar
rows or records is called a table or a file. F r o m these d e f i n
i t i o n s , y o u can see that there
is a hierarchy of data elements, as s h o w n i n Figure 5-4.
I t is t e m p t i n g to c o n t i n u e this g r o u p i n g process b
y s a y i n g t h a t a database is a
g r o u p o f tables or files. T h i s s t a t e m e n t , a l t h o u g
h t r u e , does n o t go far e n o u g h .
As s h o w n i n Figure 5-5, a database is a c o l l e c t i o n of
tables plus relationships a m o n g
t h e rows i n those tables, plus special data, c a l l e d
metadata, t h a t describes t h e
structure of the database. By the way, the c y l i n d r i c a l s y
m b o l labeled "database" i n
Figure 5-5 represents a c o m p u t e r disk drive. It is used like
this because databases are
n o r m a l l y stored o n magnetic disks.
Consider the t e r m s o n the l e f t - h a n d side of Figure 5-5.
65. You k n o w w h a t tables are.
To understand w h a t is meant b y relationships among rows in
tables, examine Figure 5-6.
It shows sample data f r o m the three tables Email, Student, and
Offlce_Visit. Notice the
c o l u m n n a m e d Student Number i n the Email table. That c
o l u m n indicates the r o w i n
Student t o w h i c h a r o w of Email is c o n n e c t e d . I n the
f i r s t r o w o f Email, the Student
Number value is 1325. This indicates that this p a r t i c u l a r e
m a i l was received from the
s t u d e n t whose Student Number is 1325. I f y o u examine
the Student table, y o u w i l l
see that the r o w for Andrea Baker has this value. Thus, the
first r o w o f the Email table is
related to Andrea Baker.
N o w consider the last r o w o f the Office_Visit table at the b
o t t o m o f the figure. T h e
value of Student Number i n that r o w is 4867. This value
indicates t h a t the last r o w i n
Office_Visit belongs to A d a m Verbena.
F r o m these examples, y o u can see t h a t values i n one table
relate rows of that table
to rows i n a second table. Several special terms are used to
express these ideas. A key
(also called a P r i m a r y Key] is a c o l u m n or g r o u p of c
o l u m n s that identifies a u n i q u e
Figure 5 *
Components of a Database
Tables or Files 1
-f-
66. Relationships
Among
Rows in Tables
+
Metadata
Database
Q2 What Is a Database? 145
Email Table
EmailNum Date Message Student Number
1 2/1/2012 For homework 1, do you want us to provide notes on
our references? . ( 1 3 2 5 )
2 3/15/2012 My group consists of Swee Lau and Stuart Nelson.
@ )
3 3/15/2012 Could you please assign me to a group? , - 1644
Student Table _ • C---
Student Number Student Name HWl HW2 MidTerm
(1325) BAKER, ANDREA 88 100 78
1644 LAU, SWEE 75 90 90
2881 NELSON, STUART 100 90 98
3007 FISCHER, MAYAN 95 100 74
67. 3559 TAM, JEFFREY 100 88
(4867>-.._^ VERBERRA.ADAM 70 90 92
5265 "VALQEZ, MARIE 80 90 85
8009 ROGERSTSHELLY 95 100 98
Off ice_Visit Table
VisitID Date Notes Student Number
2 2/13/2012 Andrea had questions about using IS for raising
barriers to entry. 1325
3 2/17/2012 Jeffrey is considering an IS major. Wanted to talk
about career opportunities. ̂ •-^ 3559
4 2/17/2012 Will miss class Friday due to j o b conflict.
row i n a table. Student Number is the key of the Student table.
Given a value of Student Example of Relationships
Number, y o u can d e t e r m i n e one a n d o n l y one r o w i n
Student. O n l y one s t u d e n t has Among Rows
the n u m b e r 1325, for example.
Every table m u s t have a k e y The key of the Email table is
EmailNum, and the key
of the Office_Visit table is VisitID. Sometimes m o r e t h a n
one c o l u m n is n e e d e d t o
f o r m a u n i q u e identifier. I n a table called City, for
example, the key w o u l d consist of
t h e c o m b i n a t i o n of c o l u m n s {City, State), because a
g i v e n c i t y n a m e can appear i n
more t h a n one state.
Student Number is n o t the key o f the Email or the
68. Office_Visit tables. We k n o w t h a t
a b o u t Email because there are t w o rows i n Email that have
the Student Number value
1325. The value 1325 does n o t i d e n t i f y a u n i q u e row,
therefore Student Number cannot
be the key of Email.
N o r is Student Number a key of Ojfice_Visit, a l t h o u g h y
o u cannot t e l l t h a t f r o m the
data i n Figure 5-6. I f y o u t h i n k about i t , however, there
is n o t h i n g to prevent a student
f r o m v i s i t i n g a professor m o r e t h a n once. I f t h a t
were to h a p p e n , there w o u l d be t w o
rows i n Office_Visit w i t h the same value of Student Number.
I t j u s t happens t h a t n o
s t u d e n t has visited twice i n the l i m i t e d data i n Figure
5-6.
I n b o t h E m a i l a n d Office_Visit, Student Number is a key,
b u t i t is a key o f a d i f f e r e n t
t a b l e , n a m e l y Student. H e n c e , t h e c o l u m n s t h a
t f u l f i l l a r o l e l i k e t h a t o f Student
Number i n the Email a n d Offtce_Visit tables are called
foreign keys. This t e r m is used
because such c o l u m n s are keys, b u t t h e y are keys of a
different (foreign) table t h a n the
one i n w h i c h they reside.
Before w e go o n , databases t h a t c a r r y t h e i r data i n t h
e f o r m o f tables a n d t h a t
represent relationships using foreign keys are called relational
databases. (The t e r m
relational is used because another, m o r e f o r m a l n a m e f o
r a t a b l e l i k e those we're
discussing is relation.) You'll learn a b o u t another k i n d o f
database, or data store, i n Q8
69. a n d i n Case Study 5.
146 CHAPTER 5 Database Processing
Metadata makes databases
easy to use, for both
authorized and unauthorized
purposes, as described in the
Ethics Guide on pages
150-151.
Metadata
Recall the d e f i n i t i o n of database: A database is a s e l f -
d e s c r i b i n g c o l l e c t i o n o f i n t e -
grated records. The records are integrated because, as y o u j u s
t learned, rows can be
t i e d t o g e t h e r b y t h e i r k e y / f o r e i g n key r e l a t i
o n s h i p . R e l a t i o n s h i p s a m o n g rows are
represented i n the database. But w h a t does self-describing
mean?
I t m e a n s t h a t a database c o n t a i n s , w i t h i n itself, a
d e s c r i p t i o n o f its c o n t e n t s .
T h i n k of a library. A l i b r a r y is a self-describing c o l l e
c t i o n of books a n d other m a t e r i -
als. I t is s e l f - d e s c r i b i n g because t h e l i b r a r y c o n
t a i n s a c a t a l o g t h a t describes t h e
l i b r a r y ' s c o n t e n t s . The same i d e a also p e r t a i n s
t o a database. Databases are
s e l f - d e s c r i b i n g because t h e y c o n t a i n n o t only
data, but also data about the data in
the database.
Metadata are data t h a t describe data. Figure 5-7 shows m e t a
70. d a t a f o r the Email
table. T h e f o r m a t of metadata depends o n the software p r
o d u c t t h a t is processing t h e
database. Figure 5-7 shows the metadata as they appear i n M i
c r o s o f t Access. Each r o w
of the t o p p a r t of t h i s f o r m describes a c o l u m n of the
Email table. The c o l u m n s of
these descriptions are Field Name, Data Type, a n d
Description. Field Name contains
the n a m e of the c o l u m n , Data Type shows the type of data
the c o l u m n m a y h o l d , and
Description contains notes that e x p l a i n the source or use of
the c o l u m n . As y o u can
see, t h e r e is o n e r o w o f m e t a d a t a f o r each o f t h e f
o u r c o l u m n s o f t h e Email t a b l e :
EmailNum, Date, Message, and Student Number.
The b o t t o m p a r t o f this f o r m provides m o r e metadata,
w h i c h Access calls Field
Properties, for each c o l u m n . I n Figure 5-7, the focus is o n
the Date c o l u m n (note the
l i g h t rectangle d r a w n a r o u n d the Date r o w ) . Because
the focus is o n Date i n the t o p
pane, the details i n the b o t t o m pane p e r t a i n to the Date
c o l u m n . The Field Properties
describe formats, a default value for Access to s u p p l y w h e
n a n e w r o w is created, and
the c o n s t r a i n t t h a t a value is r e q u i r e d for this c o l
u m n . I t is n o t i m p o r t a n t for y o u t o
r e m e m b e r these details. Instead, just u n d e r s t a n d t h a
t metadata are data about data
and that such metadata are always a p a r t of a database.
T h e presence o f m e t a d a t a makes databases m u c h m o r
e u s e f u l . Because o f
m e t a d a t a , n o one needs to guess, r e m e m b e r , or even
71. record w h a t is i n the database.
To f i n d o u t w h a t a database c o n t a i n s , w e j u s t l o o
k at t h e m e t a d a t a i n s i d e t h e
database.
Sample Metadata (in Access)
?ie!d Name
EmailNum
Date
Message
Student Number
Data Type Description
AutoN'umber Primary key -- vaiues provided by Access
Date.'Time Date aod time the message is recorded
Memo Textofthsemau
Number Foreign key to row m the Student Table
13
G«neial iiookup;
Format
Input Mask
Caption
Default -.'aius
Validation Ruli
validation Teift
Reci'.iir«d
i IME Mode
n.IE Sentence Mode
Smart Tags
Tfijd Align
Shosv Date Picker
72. Short Date
99 9-?.J0OOO,O,-
les
Ho
Mo Control
Mone
General
For date;
A fisid nmt cm be op to S4 chauder^ long,
irsd'Jtiing :ps<sf.. Press F l for rietp en fiel^
names.
Q3 What Are the Components of a Database Application
System? 147
" What Are the Components
of a Database Application System?
A database, a l l by itself, is n o t very useful. The tables i n
Figure 5-6 have all of the data
the professor wants, b u t the f o r m a t is unwieldy. The
professor wants to see the data i n
a f o r m like t h a t i n Figure 5-2 a n d also as a f o r m a t t e d
r e p o r t . Pure database data are
correct, b u t i n raw f o r m they are n o t p e r t i n e n t or
useful.
Figure 5-8 shows the c o m p o n e n t s of a database
application system. Such
a p p h c a t i o n s m a k e database d a t a m o r e accessible a
n d u s e f u l . Users e m p l o y a
73. database a p p l i c a t i o n t h a t consists of f o r m s (like that
i n Figure 5-2), f o r m a t t e d reports,
queries, a n d a p p l i c a t i o n p r o g r a m s . Each o f these,
i n t u r n , calls o n the database
m a n a g e m e n t system (DBMS) to process the database
tables. We w i l l f i r s t describe
DBMSs a n d t h e n discuss database a p p l i c a t i o n c o m p
o n e n t s .
A database management system (DBMS) is a p r o g r a m used
to create, process, a n d
a d m i n i s t e r a database. As w i t h o p e r a t i n g systems,
almost n o organization develops its
o w n DBMS. Instead, companies license DBMS p r o d u c t s f
r o m vendors s u c h as I B M ,
M i c r o s o f t , Oracle, a n d others. Popular D B M S p r o d u
c t s are D B 2 f r o m I B M , Access
and S Q L Server f r o m M i c r o s o f t , a n d Oracle Database
f r o m the Oracle C o r p o r a t i o n .
A n o t h e r p o p u l a r DBMS is MySQL, an o p e n source D
B M S p r o d u c t that is license-free
for most applications.^ Other DBMS products are available, b u
t these five process the
great b u l k of databases today.
Note that a DBMS and a database are t w o different things. For
some reason, the trade
press and even some books confuse the two. A DBMS is a
software program; a database is
a collection of tables, relationships, and metadata. The t w o are
very different concepts.
i U f ' c a t i s i g the Database and its S t r u c t u r e s
Database developers use t h e D B M S to create tables, r e l a t
i o n s h i p s , a n d o t h e r
structures i n the database. The f o r m i n Figure 5-7 can be
74. used to define a n e w table or
to m o d i f y an existing one. To create a n e w table, the
developer j u s t fills the new table's
metadata i n t o the f o r m .
To m o d i f y a n e x i s t i n g table—say, to a d d a n e w c o l
u m n — t h e d e v e l o p e r opens
the m e t a d a t a f o r m for t h a t table a n d adds a n e w r o
w of m e t a d a t a . For example, i n
Figure 5-9 t h e d e v e l o p e r has a d d e d a n e w c o l u m n
c a l l e d Response?. T h i s n e w
c o l u m n has the data t y p e Yes/No, w h i c h means t h a t
the c o l u m n can c o n t a i n o n l y
one value—Yes or No. The professor w i l l use this c o l u m n
to i n d i c a t e w h e t h e r he has
r e s p o n d e d t o the student's e m a i l . A c o l u m n can be
r e m o v e d b y d e l e t i n g its r o w i n
this table, t h o u g h d o i n g so w i l l lose any existing data.
Processing the Database
The second f u n c t i o n of the DBMS is to process the
database. Such processing can be
quite complex, but, fundamentally, the DBMS provides
applications for four processing
Forms
Reports
Queries
Application
Programs
Database
Management
System
75. User Database Application DBMS
Tables
Relationships
Metadata
Database
Components of a Database
Application System
' M y S Q L w a s s u p p o r t e d by the M y S Q L c o m p a n
y . I n 2008, that c o m p a n y w a s a c q u i r e d by S u n
M i c r o s y s t e m s , w h i c h was, in turn, a c q u i r e d by O
r a c l e later that year. B e c a u s e M y S Q L is o p e n
source,
O r a c l e does not o w n the s o u r c e code, however.