Tasos
Tasos

Reputation: 11

C# - Instantiating objects of a class that contains members of its own type?

I have searched everywhere for a solution to this problem but I can't find anything and this might be because I'm not phrasing it correctly so I'll elaborate as much as I can.

Basically the problem I'm having is figuring how to get the following scenario to work. Assume you have class "Employee" as such:

class Employee
{
    string Name { get; set; }

    Employee Manager { get; set; }

    public Employee(string name, Employee manager)
    {
        Name = name;
        Manager = manager;
    }
}

In your program you can then do this:

Employee george = new Employee("George", null);
Employee michael = new Employee("Michael", george);

But not this:

Employee michael = new Employee("Michael", george);
Employee george = new Employee("George", null);

Because obviously, the object "george" can't be used before it is declared.

This is problematic as for example I might be constructing my Employee objects by retrieving information from a database where I can't control the order in which the objects appear.

I can think of a few solutions but none seem "right" to me as they all come with a host of other problems.

I.e. I could technically instantiate every object with "Manager" set to null at first and once my list of Employees is populated, individually assign a manager to each employee that is supposed to have one. This feels like pointless overhead to a problem that probably has a much simpler solution.

So basically my question is, what is usually the correct practice for solving such an issue? Thank you in advance for your answers.

Upvotes: 1

Views: 109

Answers (1)

nvoigt
nvoigt

Reputation: 77364

I might be constructing my Employee objects by retrieving information from a database where I can't control the order in which the objects appear.

Every database can sort stuff. It's basic SQL. Even if you had unsorted data and no database, you could sort it in your program. So the answer will always be sort the data, then build your objects OR if you don't want all data made into objects, start with the one you want to get and fetch it's predecessors in a loop until you reach the first you can construct, then follow the chain you just built.

Upvotes: 1

Related Questions