C# Data Types

In the previous sections, you have learned about the Variables and Constants in C#. In this section, you will learn about the Data Types in C#. There are two categories of Data Types available in C#.

  1. Value Types
  2. Reference Types
  3. Pointer Types

Value Types & Reference Types

In simple words, the difference between value types and reference types is that value type keeps its value directly whereas reference type keeps the reference to the value. Reference types also named as objects.

In .Net the value types are stored in the stack and the reference types are stored in an area called managed heap.

Let's understand the types with an image.

C# Data Types

From the above example, you can understand the hierarchy of Data Types in C#.

Following is the syntax to declare value and reference types.

int myInt;
myInt = 0;         // initialization.

Following is the way to declare a class which is a reference type.

class Test
{
    // Methods, properties, fields, events, delegates 
    // We can add the nested classes as well here.
}

Pointer Types

Pointers in C# used to hold the memory address of another type. In C# a pointer can only hold the address of value types and arrays. Pointers are not allowed to hold the address of a reference type or the address of a structure which contains a reference type further. It's important to understand that garbage collector does not track the pointer types.

Pointers in C#

Pointer Declarations

Following is the Syntax to declare a pointer in C#:

type* identifier;  

Following are the valid and invalid pointer declarations:

int* ptr1, ptr, ptr;   // Valid declarations
int *ptr, *ptr;   // Invalid in C#  

Pointers use a different way to access the members and their values. Following are the list of operators used to perform a different kind of operations on a pointer.

Operator Description
* Used to point indirection.
-> Used to access the member of a structure using a pointer.
[] Used for the indexing pointers.
& Used to get the memory address of a variable.
++, -- Used to Increment and decrement pointers.
+, - Used to perform arithmetic operations on pointers.
==, !=, <, >, <=, and >= Used to compare pointers.
stackalloc Used to allocate memory on the stack.
fixed statement Used to fix a variable so that its address may be found.

This was an overview and explanation of Data Types in C#. Let's learn about the Data Types memory size in C# in the next Section.