Skip to content

Variables and Data Types

Sann Lynn Htun edited this page Nov 19, 2024 · 1 revision

C# Variables and Data Types

C# variables store data values, and each variable has a data type that determines the type of data it can hold and how much memory it uses. C# is a strongly typed language, meaning every variable must have a defined type.

Value Types (Stored in the stack)

Value types directly store data. Below are the value types, their sizes in memory, and ranges.

Type Bytes Range Example
byte 1 0 to 255 byte b = 255;
sbyte 1 -128 to 127 sbyte sb = -128;
short 2 -32,768 to 32,767 short s = -1000;
ushort 2 0 to 65,535 ushort us = 50000;
int 4 -2,147,483,648 to 2,147,483,647 int i = 123;
uint 4 0 to 4,294,967,295 uint ui = 4000000000;
long 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 long l = 900000;
ulong 8 0 to 18,446,744,073,709,551,615 ulong ul = 123456789;
float 4 ±1.5 × 10⁻⁴⁵ to ±3.4 × 10³⁸ float f = 3.14f;
double 8 ±5.0 × 10⁻³²⁴ to ±1.7 × 10³⁰⁸ double d = 3.14159;
decimal 16 ±1.0 × 10⁻²⁸ to ±7.9 × 10²⁸ decimal dec = 1000.99m;
char 2 Unicode characters (U+0000 to U+FFFF) char c = 'A';
bool 1 (true/false) N/A bool isTrue = true;

Reference Types (Stored in the heap)

Reference types store a reference to the data's location in memory.

Type Description Example
string A sequence of characters string name = "Alice";
object Base type of all types object obj = 42;
dynamic Type resolved at runtime dynamic dyn = "text"; dyn = 123;

Default Values

If variables are not explicitly initialized, they take default values.

Type Default Value
int 0
float 0.0f
bool false
string null
object null

Examples

1. Numeric Types

int age = 25;
float pi = 3.14f;
decimal salary = 55000.75m;
Console.WriteLine($"Age: {age}, Pi: {pi}, Salary: {salary}");

2. Boolean and Char

bool isComplete = true;
char initial = 'A';
Console.WriteLine($"Complete: {isComplete}, Initial: {initial}");

3. Strings and Objects

string name = "John Doe";
object anyValue = 42;
Console.WriteLine($"Name: {name}, Object: {anyValue}");

Summary

  • Value Types: Stored in the stack, directly hold data (e.g., int, float, bool).
  • Reference Types: Stored in the heap, hold references to data (e.g., string, object).
  • Default Values: Variables get defaults like 0 for numbers and null for references.
  • Memory Efficiency: Choose types like float or decimal based on precision needs.

C# Basics Wiki

Core Concepts

Object-Oriented Programming (OOP)

Advanced Topics

Miscellaneous

Tools and Resources

Clone this wiki locally