C sharp - C# Data Types
What Are Data Types?
In C#, data types define the type of data a variable can hold. They are crucial for memory management and ensuring type safety in applications. C# is a statically-typed language, meaning each variable must be declared with a specific data type before use. Data types in C# are broadly categorized into Value Types and Reference Types.
Value Types
Value types directly contain their data and are stored on the stack. When a value type is assigned to another variable, a copy is made. Common value types include:
-
int
– Integer type, e.g.,int age = 25;
-
float
– Single-precision floating point, e.g.,float price = 19.99f;
-
double
– Double-precision floating point, e.g.,double pi = 3.14159;
-
char
– A single Unicode character, e.g.,char grade = 'A';
-
bool
– Boolean type, eithertrue
orfalse
, e.g.,bool isOpen = true;
C# also includes smaller data types like byte
, short
, long
, and unsigned versions such as uint
and ulong
.
Reference Types
Reference types store references to the actual data, which is kept in the heap. When a reference type is assigned to another variable, both variables refer to the same object. Common reference types include:
-
string
– A sequence of characters, e.g.,string name = "Alice";
-
object
– The base type from which all other types derive. -
arrays
– E.g.,int[] numbers = {1, 2, 3};
-
class
,interface
,delegate
– Custom reference types defined by the programmer.
Nullable Types
C# also supports nullable types for value types. This means a value type can also hold a null
value, using the ?
symbol. For example:
int? score = null;
This is useful in situations where a variable might not have a value assigned yet, such as in databases or optional fields.