C# Types


This entry is part 10 of 10 in the series C# Getting Started

When you write a C# program, you are writing a set of type declarations. What is a type? A type is a template for creating data structures. It isn’t the data structure itself, but it specifies the characteristics of objects constructed from the template. The data structure is the way memory is arranged to contain the type. For example, if you need to create an integer you would use the int type. The int type (template) will define how many bytes it requires to store the data, for example. An integer in C# takes 4 bytes (32 bits). A type is defined by the following elements:

  • A name
  • A data structure to contain its data members
  • Behaviors and constraints

Instantiating a Type

Creating an actual object from the type’s template is called instantiating the type. Creating an actual object means to set aside memory for that object. The object created by instantiating a type is called either an object of the type or an instance of the type. The terms are interchangeable. Every data item in a C# program is an instance of some type provided by the language, the BCL, or another library, or defined by the programmer.

Some types, such as short, int, and long, are called simple types and can store only a single data item. Other types can store multiple data items. An array, for example, is a type that can store multiple items of the same type. The individual items are called elements and are referenced by a number, called an index.

Predefined Types

C# provides 16 predefined types which includes 13 simple types and 3 non-simple types. The names of all the predefined types consist of all lowercase characters.

The 3 non-simple (complex) types include:

  • object (the base type on which all other types are based)
  • string (an array of Unicode characters)
  • dynamic (used when using assemblies written in dynamic languages)

Simple types fall under 2 categories: non-numeric and numeric. There are 2 non-numeric types: bool and char. Numeric simple types fall under 2 categories: integer and floating point.

  • Non-numeric
    • bool
    • char
  • Numeric
    • Integer
      • sbyte
      • byte
      • short
      • ushort
      • int
      • uint
      • long
      • ulong
    • Floating Point
      • decimal
      • float
      • double

All the predefined types are mapped directly to underlying .NET types. The C# type names are simply aliases for the .NET types, so using the .NET names works fine syntactically, although this is discouraged. Within a C# program, you should use the C# names rather than the .NET names. For example, the .NET name for int is System.Int32.

User-Defined Types

Besides the 16 predefined types provided by C#, you can also create your own user-defined types. There are six kinds of types you can create:

Series Navigation<< C# Keywords