If I have created the following Employee object (simplified)...
public class Employee
{
public Employee()
{
It works, you can just try s.th. like:
public class A
{
public A test { get; set; }
}
The only scenario where this isn't possible is with a struct
; a struct
is contained directly (rather than being a fixed-size reference to the data), so the size of an Employee
struct would have to be "the size of the other fields plus the size of an Employee", which is circular.
In particular you can't have:
struct Foo {
Foo foo;
}
(or anything else that would result in a circular size) - the compiler responds with:
Struct member 'Foo.foo' of type 'Foo' causes a cycle in the struct layout
However, in all other cases it is fine; with the issue of initialisation, I'd say: just leave it unassigned initially, and let the caller assign a value via the property.
I tried this way and it worked for me:
class Program
{
static void Main(string[] args)
{
A a = new A(new A());
}
}
public class A
{
public string Name { get; set; }
public A a;
public A() { }
public A(A _a)
{
a = _a;
}
}
Now you can use it in the Main() function like:
class Program
{
static void Main(string[] args)
{
A a = new A(new A());
a.Name = "Roger";
a.a.Name = "John";
Console.WriteLine("{0}, {1}", a.Name, a.a.Name);
}
}
An object can indeed have a reference to an object of its own type.
This is how most Node
type objects are implemented.
As for instantiation - you can pass in the Employee
object to use as manager (passing in null for no manager). Constructors can have multiple overloads:
public Employee(Employee manager)
{
this.Manager = manager;
}
Yes, you can have Employee
inside Employee
and it will not cause infinite loop, by default Manager
property of Employee
object will be null
.
Yes, an object can contain references to other objects of the same class.
And secondly, I wouldn't create a new Employee in the cunstructor but inject it like this:
public class Employee
{
public Employee(Employee manager)
{
this.Manager = manager;
}
public String StaffID { get; set; }
public String Forename { get; set; }
public String Surname { get; set; }
public Employee Manager { get; set; }
}