C# Data Types

In this lesson, you will learn about Data Types in C# and their usage, along with examples to better understand the topic.


Data Type in C#

In C#, you must indicate the type when declaring a variable since it’s a strongly typed programming language.

Example

String studentName;

Data Types Categories in C#

C# data types can be divided into three categories:

  • Value Data Types: int, bool, char, double, float, etc.
  • Reference Data Types: string, class, object, interface, delegate, etc.
  • Pointer Data Type: Pointers.

Value Data Types in C#

The value data types can be assigned a value directly, such as an integer.
The following tables represent the most used value types in C#

Type NameSize (In Byte)Range
Bool1 True/False
Byte10 to 255
Char1U +0000 to U +ffff
Short2-32,768 to 32,767
signed short2-32,768 to 32,767
unsigned short20 to 65,535
int4-2,147,483,648 to 2,147,483,647
signed int4-2,147,483,648 to 2,147,483,647
unsigned int40 to 4,294,967,295
long8-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
signed long8-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
unsigned long80 to 18,446,744,073,709,551,615
float4-3.4 x 1038 to + 3.4 x 1038
double8(+/-)5.0 x 10-324 to (+/-)1.7 x 10308
decimal16(-7.9 x 1028 to 7.9 x 1028) / 100 to 28

Example of values data types in C#

Reference Data Types in C#

As its name indicates, a reference data type contains a reference to a memory location, not the data stored in the variable.

There are three reference data types in C#: Object, Array, and String Types.

1 – Object Type

In the .NET framework, every type is derived from an object. You can convert an object type to a value data type and vice versa by boxing and unboxing. Boxing is when a value type is converted to an object type, while unboxing is when an object type is converted to a value type.

Example

2 – Arrays

Arrays are another reference type in C#. they are an indexed collection of data of the same type.

Example

string[] students;
int[] grades;

We will discuss Arrays in detail later in this course.

3 – String Types

String type is another Reference Type in C#. It represents a sequence of Unicode characters that you can use to store string data, such as names, countries, months, etc.

Example


Pointer Data Type

In C#, a pointer datatype store the address in the memory or another datatype.

The syntax of a pointer is:

datatype* identifier;

Example of pointers in C#

using System;
namespace PointerDemo {
  class Example {
    public static unsafe void PointerTest() {
      int number = 10;
      int * pointer = & number;
      Console.WriteLine("The value is: " + number);
      Console.WriteLine("The address of the value is: " + (int) ptr);
    }

    public static void Main() {
      PointerTest();
    }

  }

}

We will discuss pointers in detail and their usage later in this course.

This concludes the C# Data Types lesson. In the next lesson, you will learn Type Casting in C#.