Reputation: 234
Is there a better way of instantiating an object say for example has the same type as a property in it. As in the example below, I have an Employee class containing property Manager of type Employee,
class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
}
if instantiated
Employee n1 = new Employee{
Name="emp1",
Manager = new Employee(){
Name="mgr1",
Manager= new Employee(){ ...
The instantiation would go on till we reach the top level now in case the organization heirarchy is huge (please assume may be 500 levels) is there a better way to instantiate.
Upvotes: 0
Views: 119
Reputation: 18127
//this in main or whetever you use it.
Employee n1 = new Employee();
Employee manager = new Employee();
manager.IsCEO = true;
manager.Name = "Manager Name";
n1.Name = "John";
n1.Manager = manager;
class Employee
{
private Employee _manager = new Employee();
public string Name { get; set; }
public bool IsCEO{ get; set;}
public Employee Manager
{
get
{
if(IsCEO)
return null;
else
return _manager;
}
set
{
if(!IsCEO)
_manager=value;
}
}
}
Something like this ?
Upvotes: 0
Reputation: 52290
Well why not declarative:
class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
public static Employee CreateBigBoss(string name) // insert a enterprisey name here
{
return new Employee { Name = name, Manager = null };
}
public Employee CreateSubordinate(string name)
{
return new Employee { Name = name, Manager = this };
}
}
use it like this:
var burns = Employee.CreateBigBoss("Mr Burns");
var smithers = burns.CreateSubordinate("Mr Smithers");
Upvotes: 1
Reputation: 1370
Nested classes are classes declared inside the declaration of another class.
What you are describing is nested instances and you did it fine.
This is a nested class:
class MyOuterClass {
string outerClassName { get; set; }
class MyInnerClass {
string innerClassName { get; set; }
}
MyInnerClass myInnerClass = new MyInnerClass() {
innerClassName = "inner";
}
}
Most situations don't call for an inner class.
Upvotes: 0