C# DataType

In C#, data types define the type of data that a variable can store. Each data type determines the size and the type of value that can be stored in memory. C# provides both primitive data types (e.g., integers, floating-point numbers, etc.) and reference data types (e.g., objects, arrays).

Integer Types

These data types store whole numbers (without decimals). They differ in the range of values they can hold.

int

it stores a 32-bit signed integer and It has Range between -2,147,483,648 to 2,147,483,647.

Example:


int age = 35; 

long

It stores a 64-bit signed integer and it has Range between -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Example:


long watchEpisode = 9800000000L;  // Use 'L' suffix for long literals

short

It stores a 16-bit signed integer and It has Range between -32,768 to 32,767.

Example:


short num = 450; 

byte

It stores an 8-bit unsigned integer and It has Range between 0 to 255.

Example:


byte data = 125; 

Floating-Point Types

These data types store numbers with decimal points.

float

It stores a 32-bit floating-point number, The precision of floating point value can have 7 digits.

Example:


float data = 6.8f;  // Use 'f' suffix for float literals

double

It stores a 64-bit floating-point number. The precision of floating point value can have up 15-16 digits.

Example:


float data = 98.86; 

decimal

It stores a 128-bit precise decimal number (useful for financial calculations). The precision of floating point value can have up 28-29 digits.

Example:


decimal price = 29.99m;  // Use 'm' suffix for decimal literals

String Type

It stores a sequence of characters (a string of text).

Example:


string name = "John Taylor";

Boolean Type

It stores a value of true or false.

Example:


bool isUserAdmin= true;
bool isActive =  false;

Object Type

It can store any data type, but it needs to be cast back to its original type for manipulation.

Example:


object obj = 1234;  // Stores an integer value
obj = "Hello World";     // Can also store a string value

Nullable Types

C# also allows you to create nullable types, which are types that can hold a value or null. You can declare any value type (like int, double, etc.) as nullable by adding a ? after the type name. This means the variable can hold either a valid value or null.

Example:


string? name = null;  // Nullable string, can be null or hold a value

Reference Types (arrays, classes, interfaces)

string: A reference type, holds a sequence of characters.

Arrays: Arrays hold collections of values of the same type.

Example:


int[] numbers = { 1, 2, 3, 4, 5 };

Classes: Define custom types (not built-in) for objects.

Example:


class Employee {
    public string name{ get; set; }
    public int age { get; set; }
}