0

I have made an list employee data app in C# with functions like AddEmployee, DeleteEmployee, SearchEmployee. I would like to make the same program, but using Singleton design pattern. I know the structure of Singleton, but I messed up with making the list and then adding the actual employee into the list.

Here is a portion of my program:

class Student : IComparable<Student>
{
    //public int id;
    public string name;
    public decimal salary;
    public string position;
    public int intern;

    public Student(string name, string position, int intern, decimal salary)
    {
        this.name = name;
        this.position = position;
        this.intern = intern;
        this.salary = salary;
    }

public string Name { get; set; }
public decimal Salary { get; set; }
public string Position { get; set; }
public int Intern { get; set; }

    public void CalculateSalary()
    {
        salary = 1000 * intern;
    }

    public override string ToString()
    {
        return "Name: " + name + "\t Position: " + position + "\t Intern: " + intern + "\t Salary: " + salary;
    }

    /// <summary>
    /// Gets student information from the user and adds a new student to the list
    /// </summary>
    /// <param name="existingStudents">The list of students to add to</param>
    private static void AddStudent(List<Student> existingStudents)
    {
        string ans = "";
        do{

            // Initialize the list if it's null
            if (existingStudents == null) existingStudents = new List<Student>();

            int tempInt;

            // Get student information from the user
            Console.WriteLine("Enter new student information");

            Console.Write(" 2. Enter student Name: ");
            var name = Console.ReadLine();

            Console.Write(" 3. Enter student Job Title: ");
            var jobTitle = Console.ReadLine();

            do
            {
                Console.Write(" 4. Enter student years of service: ");
            } while (!int.TryParse(Console.ReadLine(), out tempInt));
            var yrsOfService = tempInt;

            var salar = tempInt;

            // Add the new student to the list
            existingStudents.Add(new Student(name, jobTitle, yrsOfService, salar));

            foreach (Student stud in existingStudents)
            {
                stud.CalculateSalary();
                Console.WriteLine(stud.ToString());
            }
            Console.WriteLine("Do you want to add another Student? y/n");
            ans = Console.ReadLine();
        } 
        while (ans != "n");
    }

In the main program I have a list and call the addStudent function:

             List<Student> st = new List<Student>();

        int answer = 1;
        do
        {
            Console.WriteLine("============================");
            Console.WriteLine("2. Read From File");
            Console.WriteLine("3. Add Student...");

            answer = Convert.ToInt32(Console.ReadLine());

            switch (answer)
            {
                case 2:
                    JustReadFromFile(st, filePath);
                    break;
                case 3:
                    AddStudent(st);
                    break;
                case 4:
                    Console.WriteLine("Exit Menu...");
                    break;
            }
        } while (answer != 4);

List st = new List();

I know that I have to make a private static instance.

   private static Student st;

Also, there should be a private Student constructor instead of mine above.

   private Student() { }    

And this is the method which will create my new student. I also think that I need a similar method to create my list, but I am not sure.

   public static Student getInstance()
{
    if (st == null)
        st = new Student();
    return st;
}

Can you give some directions and advice please. Thank you

Kaloyan
  • 41
  • 5

2 Answers2

0
public class Student
{
    private static Student instance = null;
    private static readonly object locker = new object();

    public static Student Instance
    {
        get
        {
            lock (locker)
            {
                if (instance == null)
                {
                    instance = new Student();
                }

                return instance;
            }
        }
    }

    public void SomeMethod()
    {
    }
}

Then you access the Student instance like this: Student.Instance.SomeMethod();

0

Student class:

public class Student
{
    public string Name { get; set; }
    public decimal Salary { get; set; }
    public string Position { get; set; }
    public int Intern { get; set; }
}

StudentData singleton (you could alternatively make the the List<Student private and create methods inside the Singleton class itself to interact with the list and get/add data to it, but I left it public for the simplicity of the example):

public class StudentData
{
    private static readonly StudentData _studentData = new StudentData();

    public List<Student> Students { get; set; }

    private StudentData()
    {
        Students = new List<Student>();
    }

    public static StudentData GetInstance()
    {
        return _studentData;
    }
}

Usage like this:

        var studentData = StudentData.GetInstance();

        //Get all students in the singleton
        var students = studentData.Students;

        //Add new student
        studentData.Students.Add(new Student());
        studentData.Students.Add(new Student
        {
            Intern = 1,
            Name = "SomeName"
        });

Hopefully this will get you going to the right direction.

Vidmantas Blazevicius
  • 4,652
  • 2
  • 11
  • 30
  • I managed to add the data using the singleton class. I created a function to add them to a text file public void WriteToFile(List Students, string filePath) { StreamWriter writer = new StreamWriter(filePath, true); foreach (Student stud in Students) {writer.WriteLine(stud.ToString()); } writer.Close();} , but I prefer to write the data to my sql server database table. I already have the table, but have trouble connecting it to my application. Can you give me a recommendation how to do it? – Kaloyan Mar 17 '18 at 22:43
  • @Kaloyan You should close this question first if it has helped you and open a new one with what is not working for you in regards to your connection issue with the code samples. I won't be able to help you with your sql issue in the comments as it could be anything. – Vidmantas Blazevicius Mar 17 '18 at 22:47
  • Thank you. Appreciate your help a lot. – Kaloyan Mar 18 '18 at 10:46