I have a class Reservation where all the information comes from 2 other classes Customer and Voertuig.
I need to read the written information in the Reservation text file and I'm receiving the errors "Invalid initializer member declarator." and "Collection initializer requires its type 'Reservation' to implement System.Collections.IEnumerable."
Here is my Reservation class:
public class Reservation
{
public string fullpath = $@"{AppDomain.CurrentDomain.BaseDirectory}\Reservation.txt";
private Customer _customer;
private Voertuig _vehicle;
public Customer Customers
{
get { return _customer ?? (_customer = new Customer()); }
set { _customer = value; }
}
public Voertuig Vehicles
{
get { return _vehicle ?? (_vehicle = new Voertuig()); }
set { _vehicle = value; }
}
public Reservation(): this(new Customer(), new Voertuig())
{
}
public Reservation(Customer customer, Voertuig vehicle)
{
_customer = customer;
_vehicle = vehicle;
}
public void Create()
{
try
{
if (File.Exists(fullpath))
{
StreamWriter sw = new StreamWriter(fullpath, true);
var record = $"{Customers.Firstname};{Customers.Lastname};{Customers.Age};{Customers.Phonenumber};{Vehicles.Type};{Vehicles.Electric};{Vehicles.RequiredAge};{Vehicles.Wheels};{Vehicles.PersonsCanRide};{Vehicles.AllowedSpeed}";
sw.WriteLine(record);
sw.Close();
sw.Dispose();
}
}
catch (IOException ioex)
{
throw new Exception(ioex.Message);
}
}
public List<Reservation> ReadFromCsv()
{
List<Reservation> _reservation = new List<Reservation>();
try
{
if (File.Exists(fullpath))
{
using (StreamReader reader = new StreamReader(fullpath))
{
string record = reader.ReadLine();
while (record != null)
{
string[] fields = record.Split(new char[] { ';' });
Reservation res = new Reservation
{
// error CS1922: Cannot initialize type 'Reservation' with a collection initializer
// because it does not implement 'System.Collections.IEnumerable'
// error CS0747: Invalid initializer member declarator
Customers.Firstname = fields[0],
Customers.Lastname = fields[1],
};
_reservation.Add(res);
record = reader.ReadLine();
}
}
}
}
catch (IOException ioEx)
{
throw new Exception(ioEx.Message);
}
return _reservation;
}
}
I reviewed this question but seems like it's not the same problem.
Do I need to create properties in the Reservation class for all Customer and Vehicle properties?
CodePudding user response:
You can work around the error by initializing your Reservation class like this instead:
Reservation res = new Reservation
{
Customers = new Customer
{
Firstname = fields[0],
Lastname = fields[1]
}
};
Initializers are meant to set properties within a class, but what you're trying to do is set the properties of a class within the class (the customers class).
What I do here is create an object initializer for Customer and then set Reservations' Customers property to the new Customer instance.