Different Data Types in C#
๐ก Concept: C# Data Types
Data types in C# determine the kind of data a variable can hold. C# has a rich set of built-in types, categorized into value types and reference types, which serve as the foundation for writing strongly-typed code.
๐ Quick Intro to Data Types
C# supports simple types like int
, float
, char
, and bool
, as well as complex types like class
, interface
, delegate
, and more. Understanding how and when to use them is essential for safe and efficient programming.
๐ง Analogy: Think of a Warehouse
Imagine a warehouse where each item is stored in a labeled box (type). Value types are like sealed boxes with the item inside, passed around by copying. Reference types are like warehouse tickets that point to the actual item. You hand out references, not copies of the box.
๐ง Technical Explanation
- Value Types: Store the actual data. Examples:
int
,float
,bool
,struct
. - Reference Types: Store a reference to the data. Examples:
class
,interface
,delegate
. - Nullable Types: Allow value types to be null using
?
, e.g.,int?
. - Object Type: Base type of all types in C#.
- Dynamic Type: Runtime-resolved type, declared using
dynamic
.
๐ฏ Use Cases
- Use value types when performance is critical and memory layout matters (e.g., in games, math).
- Use reference types for complex data models and shared access (e.g., web APIs, services).
- Use nullable types when a value might be missing (e.g., optional form inputs).
๐ป C# Code Example
int count = 10; // value type
string name = "Alice"; // reference type
int? score = null; // nullable value type
object obj = count; // boxing to object
dynamic user = GetUser(); // dynamic type resolved at runtime
