Click here to Skip to main content
15,886,735 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all. I have little problem.
In first method of my code I've loaded data about students from TXT file to List<Student> collection. There are more types of students (classes PrimaryStudent, SecondaryStudent, HightSchoolStudent, UniversityStudent, ExternStudent etc...)
Now, in other method I want to save every kind of Student to different directory. My problem is in that I have all objects in one collection in that interface. How can now I differentiate or what should I do to differentiate all types of students? Please help.
Posted
Updated 5-May-12 11:09am
v2
Comments
VJ Reddy 6-May-12 3:19am    
Thank you for accepting the solution.

1 solution

There are two alternatives.

  1. If a method or property can be introduced in the classes, then declare an abstract or virtual method or property in the Student class and override it in the derived classes to return an appropriate directory to save that class, which can be used for saving.
  2. Check the object against the classes of Students and save to different directories accordingly as shown below.
  3. Here to demonstrate the idea I have used Console.WriteLine. The string can be used for saving to a directory with that name using appropriate code.
    C#
    void Main()
    {
        List<Student> students = new List<Student>();
        students.Add(new PrimaryStudent());
        students.Add(new SecondaryStudent());
    
        //Alternative 1 If a method or property can be introduced
        //in the Derived classes
        students.ForEach(s => Console.WriteLine (s.GetDirectoryToSave()));
    
        //Alternative 2
        students.ForEach(s => {
            if (s is PrimaryStudent)
                Console.WriteLine (@"C:\PrimaryStudent");
            else if (s is SecondaryStudent)
                Console.WriteLine(@"C:\SecondaryStudent");
    
        });
    }
    
    public abstract class Student {
        public abstract string GetDirectoryToSave();
    
    }
    
    public class PrimaryStudent : Student {
        public override string GetDirectoryToSave(){
            return @"C:\PrimaryStudent";
        }
    }
    public class SecondaryStudent : Student {
        public override string GetDirectoryToSave(){
            return @"C:\SecondaryStudent";
        }
    }
 
Share this answer
 
v2
Comments
Sandeep Mewara 5-May-12 14:32pm    
My 5!
Shahin Khorshidnia 5-May-12 17:10pm    
Yes, Me too
VJ Reddy 5-May-12 20:42pm    
Thank you, Shahin.
VJ Reddy 5-May-12 20:40pm    
Thank you, Sandeep.
Mohammad A Rahman 5-May-12 20:28pm    
Good use of Polymorphism! I would use your Alternative option 1 as that make perfect sense.
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900