.NET Fundamentals: Types
In .NET, everything is a type. Types define the structure and behavior of data. Understanding types is fundamental to writing robust and efficient C# code. .NET categorizes types into two main groups: value types and reference types.
Value Types
Value types directly contain their data. When you assign a value type to another variable, the data is copied. This means changes to one variable do not affect the other.
Common Built-in Value Types:
Type | Description | Example |
---|---|---|
int |
32-bit signed integer | int count = 10; |
double |
64-bit floating-point number | double price = 99.99; |
bool |
Boolean (true or false ) |
bool isComplete = true; |
char |
16-bit Unicode character | char initial = 'A'; |
struct |
User-defined composite types | struct Point { public int X; public int Y; } |
enum |
User-defined enumerated types | enum Color { Red, Green, Blue } |
Value Type Assignment Example
int a = 5;
int b = a; // b gets a copy of the value 5
b = 10; // Changing b does not affect a
Console.WriteLine($"a: {a}"); // Output: a: 5
Console.WriteLine($"b: {b}"); // Output: b: 10
Reference Types
Reference types store a reference (or pointer) to the location of their data in memory. When you assign a reference type to another variable, both variables point to the same object. Changes made through one variable will be visible through the other.
Common Built-in Reference Types:
string
: Immutable sequence of Unicode characters.class
: User-defined composite types.interface
: Contracts for classes.array
: Collections of elements of the same type.delegate
: Type-safe function pointers.
Reference Type Assignment Example
class MyClass { public int Value; }
MyClass obj1 = new MyClass();
obj1.Value = 5;
MyClass obj2 = obj1; // obj2 now refers to the same object as obj1
obj2.Value = 10; // Changing obj2.Value also changes obj1.Value
Console.WriteLine($"obj1.Value: {obj1.Value}"); // Output: obj1.Value: 10
Console.WriteLine($"obj2.Value: {obj2.Value}"); // Output: obj2.Value: 10
Boxing and Unboxing
Boxing is the process of converting a value type to a reference type (e.g., int
to object
).
Unboxing is the process of converting a reference type back to a value type. These operations involve memory allocation and can impact performance.
Boxing and Unboxing Example
int number = 123;
object boxedNumber = number; // Boxing
int unboxedNumber = (int)boxedNumber; // Unboxing
Console.WriteLine($"Boxed: {boxedNumber}"); // Output: Boxed: 123
Console.WriteLine($"Unboxed: {unboxedNumber}"); // Output: Unboxed: 123
Understanding the distinction between value types and reference types is crucial for managing memory, avoiding unexpected side effects, and writing efficient .NET applications.