C#C
C#3y ago
bernie2024

❔ ✅ Struggling with function showing error, "Object reference not set to an instance of an object"

have been trying to solve this issue, not sure what the problem is. public static class CustomerDB
{
private const string dir = @"C:\C#\Files";
private const string path = dir + "Customers.txt";
public static void SaveCustomers(List<Customer> customers)
{
// create the output stream for a text file that exists
StreamWriter textOut =
new StreamWriter(
new FileStream(path, FileMode.Create, FileAccess.Write));

// write each customer
foreach (Customer customer in customers)
{
textOut.Write(customer.FirstName + "|");
textOut.Write(customer.LastName + "|");
textOut.WriteLine(customer.Email);
}

// write the end of the document
textOut.Close();
}
I get the error "Exception Thrown System.NullReferenceException: 'Object reference not set to an instance of an object. customers was null."

If any additional reference code is needed for context I can provide it, the point of this is to add a "Customer" to a database of customers

What am I doing wrong here? it only has the issue once reaching the 'Foreach (Customer customer in customers)' statement.
Was this page helpful?