Introduction to Data Persistence in C#
Why We Need Persistent Data
When a program runs, it uses RAM (Random Access Memory) to store data that it needs while executing.
RAM is fast but volatile --- meaning that all data stored in it is lost when:
- The application closes
- The computer shuts down or restarts
- The process crashes
Therefore, if our application needs to remember data between runs --- for example, user preferences, scores in a game, or saved records --- we need a way to persist this data to a non-volatile storage medium (e.g., hard drive or SSD).
Ways to Persist Data
1. Saving Data to Files
The simplest form of persistence is writing data to files on disk.
In C#, we can use classes from the System.IO namespace such as:
FileStreamWriter/StreamReaderFileStream
Example (writing text to a file):
File.WriteAllText("data.txt", "Hello, world!");Example (reading text from a file):
string content = File.ReadAllText("data.txt");
Console.WriteLine(content);We can also use structured Data Formats such as CSV, JSON, or XML for better organization and interoperability.
2. Using Databases
A database is a more structured and powerful way to persist and manage data. It allows multiple users or applications to access and modify data concurrently and provides mechanisms for:
- Querying data efficiently
- Enforcing relationships between data
- Ensuring data integrity
There are two main categories of databases:
a) Relational Databases (SQL)
Examples: - SQLite - MySQL - PostgreSQL - Microsoft SQL Server
They store data in tables with rows and columns, and data is accessed using SQL (Structured Query Language).
Example of a simple SQL table definition:
CREATE TABLE Students (
Id INTEGER PRIMARY KEY,
Name TEXT,
Grade INTEGER
);b) NoSQL Databases
Examples: - MongoDB - Redis - CouchDB
These are often used for unstructured or semi-structured data, offering more flexibility in data storage models such as documents, key-value pairs, or graphs.
3. The Common Ground
Even though databases appear to “magically” store and retrieve data, they too must write to persistent storage (usually disk). Whether we save data as a file or store it in a database, ultimately the data ends up on some form of persistent medium to survive program termination.
💡 Key takeaway: RAM is temporary; persistence means saving data in a non-volatile way so it can be restored later.