Type Basics

A type defines the blueprint for a value. A value is a storage location denoted by a variable or a constant. A variable represents a value that can change, whereas a constant represents an invariant. We created a local variable named x in our first program:

	static void Main( )
	{
	  int x = 12 * 30;
	  Console.WriteLine (x);
	}

All values in C# are instances 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 is int.

Predefined Type Examples

Predefined types are types that are specially supported by the compiler. The int type is a predefined primitive type for representing the set of integers that fits 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 the string type. The string type represents a sequence of characters, such as “.NET” or http://oreilly.com. We can manipulate 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 primitive bool type has exactly two possible values: true and false. The bool type is commonly used to conditionally branch execution flow based with an if statement. For example:

 bool simpleVar = false; if (simpleVar) Console.WriteLine ...

Get C# 3.0 Pocket Reference, 2nd 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.