Clarkinator
Clarkinator

Reputation: 79

Unable to cast object to list

I have a section of code where I'm trying to cast an object that I made to a list and it won't cast the object to the list. I have no idea why this is occuring.

FileStream fs = new FileStream("students.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
List<Student> studentList = (List<Student>)bf.Deserialize(fs);

This code errors on the last line saying:

Unable to cast object of type 'Project.Student' to type 'System.Collections.Generic.List`1[Project.Student]'.

The object creation looks like this:

[Serializable]
class Student
{
    private String name;
    private String surname;
    private String id;
    private int lab;
    private int assign1;
    private int assign2;
    private int exam;

    public Student(String name, String surname, String id)
    {
        this.name = name;
        this.surname = surname;
        this.id = id;
        this.lab = 0;
        this.assign1 = 0;
        this.assign2 = 0;
        this.exam = 0;
    }
    public Student(String name, String surname, String id, int lab, int assign1, int assign2, int exam)
    {
        this.name = name;
        this.surname = surname;
        this.id = id;
        this.lab = lab;
        this.assign1 = assign1;
        this.assign2 = assign2;
        this.exam = exam;
    }
}

I'm just trying to work out why it won't cast the object to the list when it has done so in the past. Any help on this matter would be greatly appreciated.

Upvotes: 0

Views: 1001

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61379

The error would seem to indicate that you serialized a Student and not a List<Student>.

If there is a possibility of either being serialized, then just check the cast and make a new list for the Student case:

object readObject = bf.Deserialize(fs);
if (readObject is List<Student>)
   return (List<Student>)readObject
else if (readObject is Student)
   return new List<Student>() { (Student)readObject };
else
   return null;

Upvotes: 1

Related Questions