Insects + Persistence - C# Programming Exercise

In this exercise, you need to create a new version of the insects exercise where the data is persisted using some form of storage, such as a database or file system. The goal is to learn how to handle data persistence in C# through databases or files. To accomplish this, you will implement a mechanism to store and retrieve information related to the insects, allowing the data to persist even after the program is closed. This exercise will help you understand how to interact with databases or the file system to save information, which is an essential skill in developing applications that require managing large amounts of data or maintaining long-term records.

By implementing data persistence in the insects exercise, you will learn how to create tables or files to store data, as well as how to perform read and write operations on them. Additionally, you will explore how to manage the lifecycle of data in an application, from creation and storage to retrieval and updating.

 Category

Object Persistence

 Exercise

Insects + Persistence

 Objective

Create a new version of the "insects" exercise, which should persist the data using some form of storage such as a database or file system.

 Write Your C# Exercise

// Importing necessary namespaces for file I/O operations and general functionality
using System; // To use general .NET functionalities
using System.Collections.Generic; // To use List for storing insect objects
using System.IO; // To perform file I/O operations

// Define a class to represent an Insect
class Insect
{
    public string Name { get; set; } // Name of the insect
    public string Color { get; set; } // Color of the insect
    public double WingSpan { get; set; } // Wing span of the insect (in centimeters)
    
    // Constructor to initialize the insect's properties
    public Insect(string name, string color, double wingSpan)
    {
        Name = name; // Assign name to the insect
        Color = color; // Assign color to the insect
        WingSpan = wingSpan; // Assign wing span to the insect
    }
    
    // Method to represent the insect as a string (for easy display and storage)
    public override string ToString()
    {
        return $"{Name},{Color},{WingSpan}"; // Return insect data as a comma-separated string
    }
}

// Define a class to handle the persistence (save/load) of Insect data to/from a file
class InsectDataPersistence
{
    private const string FilePath = "insects_data.txt"; // File path for storing insect data

    // Method to save a list of insects to a file
    public void SaveInsectsToFile(List insects)
    {
        try
        {
            // Open the file for writing (it will overwrite any existing data)
            using (StreamWriter writer = new StreamWriter(FilePath, false))
            {
                // Write each insect's data as a new line in the file
                foreach (var insect in insects)
                {
                    writer.WriteLine(insect.ToString()); // Save the insect as a string
                }
            }
            // Notify that the data has been saved successfully
            Console.WriteLine("Insect data has been saved to the file.");
        }
        catch (Exception ex)
        {
            // Display an error message if something goes wrong
            Console.WriteLine($"Error saving insect data to file: {ex.Message}");
        }
    }

    // Method to load a list of insects from a file
    public List LoadInsectsFromFile()
    {
        List insects = new List(); // List to store the loaded insects

        try
        {
            // Open the file for reading
            using (StreamReader reader = new StreamReader(FilePath))
            {
                string line;
                // Read each line of the file
                while ((line = reader.ReadLine()) != null)
                {
                    // Split the line into parts (name, color, wing span)
                    var parts = line.Split(',');

                    // Create a new Insect object and add it to the list
                    insects.Add(new Insect(parts[0], parts[1], double.Parse(parts[2])));
                }
            }
            // Notify that the data has been loaded successfully
            Console.WriteLine("Insect data has been loaded from the file.");
        }
        catch (Exception ex)
        {
            // Display an error message if something goes wrong
            Console.WriteLine($"Error loading insect data from file: {ex.Message}");
        }

        return insects; // Return the list of loaded insects
    }
}

// Main class to demonstrate the insect data persistence functionality
class Program
{
    static void Main(string[] args)
    {
        // Create a list of insects with sample data
        List insects = new List
        {
            new Insect("Dragonfly", "Green", 15.5),
            new Insect("Butterfly", "Yellow", 10.2),
            new Insect("Bee", "Black and Yellow", 3.1)
        };

        // Create an instance of InsectDataPersistence to handle file operations
        InsectDataPersistence persistence = new InsectDataPersistence();

        // Save the insect data to the file
        persistence.SaveInsectsToFile(insects);

        // Load the insect data from the file
        List loadedInsects = persistence.LoadInsectsFromFile();

        // Display the loaded insects' data
        Console.WriteLine("\nLoaded Insects:");
        foreach (var insect in loadedInsects)
        {
            Console.WriteLine($"Name: {insect.Name}, Color: {insect.Color}, Wing Span: {insect.WingSpan} cm");
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of Object Persistence

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Cities - persistence

    In this exercise, you need to create a new version of the cities database, using persistence to store its data instead of text files. The goal of this exercise...

  •  Table + array + files

    In this exercise, you are asked to expand the previous exercise (tables + array) by adding two new methods. The first of these methods should handle dumping the array...

  •  Table + SetOfTables + files

    In this exercise, you are asked to expand the previous exercise (tables + array + files) by creating three new classes: Table, SetOfTab...