Classes and Structures in Visual Basic
Understanding Types
VB.NET provides two primary ways to define complex data structures: classes (reference types) and structures (value types). Choose a class when you need inheritance, polymorphism, or large immutable objects. Use a structure for small, immutable data that benefits from stack allocation.
Show Example ►
Key Differences
Aspect | Class | Structure |
---|---|---|
Memory Allocation | Heap (reference type) | Stack (value type) |
Inheritance | Supports inheritance | No inheritance (except interfaces) |
Default Constructor | Can define none; compiler provides one | Must have parameterless constructor automatically |
Assignment | Copies reference | Copies entire value |
Nullability | Can be Nothing | Cannot be Nothing (except Nullable(Of T)) |
When to Use a Structure
- Data is small (typically < 16 bytes).
- Immutability is desired.
- Frequent creation and disposal (e.g., points, colors).
- No need for inheritance.
When to Use a Class
- Complex behavior requiring methods, events, or inheritance.
- Object lifetimes managed via garbage collection.
- Large data that would be costly to copy.
- Polymorphic collections.
Best Practices
- Prefer
Class
for most scenarios. - Make structures immutable: declare
ReadOnly
fields and provide a constructor. - Implement
IEquatable(Of T)
for structures to improve equality checks. - Avoid exposing mutable reference fields in structures.