Type Basics
A type defines the blueprint for a value. A
value is a storage location denoted by a
variable (if it can change) or a
constant (if it cannot). We created a local variable
named x
in our first program.
All values in C# are an instance of a specific
type. The meaning of a value, and the set of possible values a variable
can have, is determined by its type. The type of x
in our example program is int
.
Predefined Type Examples
Predefined types (also called built-in types) are types that are specially
supported by the compiler. The int
type is a
predefined type for representing
the set of integers that fit into 32 bits of memory, from
‒231 to 231‒1. We
can perform functions such as arithmetic with instances of the int
type as follows:
int x = 12 * 30;
Another predefined C# type is string
. The string
type represents a sequence of
characters, such as “.NET” or “http://oreilly.com”. We can work with strings by calling
functions on them as follows:
string message = "Hello world"; string upperMessage = message.ToUpper(); Console.WriteLine (upperMessage); // HELLO WORLD int x = 2007; message = message + x.ToString(); Console.WriteLine (message); // Hello world2007
The predefined bool
type has exactly
two possible values: true
and
false
. The bool
type is commonly used to conditionally
branch execution flow with an if
statement. For example:
bool simpleVar = false; if (simpleVar) Console.WriteLine ("This will not print"); int x = 5000; bool lessThanAMile = x < 5280; if (lessThanAMile) Console.WriteLine ...
Get C# 4.0 Pocket Reference, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.