Reputation: 4259
I am just trying out some things in c# and i came across this where i have created an object for the same class in the class itself
class Class1
{
public int test1 { get; set; }
Class1 x = new Class1();
}
and then i have tried to create object from an other class which is throwing an error
An unhandled exception of type 'System.StackOverflowException' occurred in Test.exe
class Program
{
static void Main(string[] args)
{
Class1 x = new Class1();
}
}
i have googled and i havent found any related links to c# but i found it in c++ where they say a Class1 is an incomplete type, as it has not been defined yet, rather it's being defined. I would like to know whether its the same case for c# also
Upvotes: 3
Views: 7272
Reputation: 1
why do you need to create the object in the class, why don't you use "this" keyword. This way it will always points towards the current object but just in case you want a fresh object then create another function in the class and then create the object it will work.
Upvotes: 0
Reputation: 236188
Just don't create instance of Class1
during creation of Class1
instance. Put a placeholder instead:
class Class1
{
public int test1 { get; set; }
public Class1 AnotherClass1;
}
And provide reference to another (already created instance) either after creation or during creation as constructor argument:
static void Main(string[] args)
{
Class1 x = new Class1();
x.AnotherClass1 = new Class1();
}
Upvotes: 0
Reputation: 223187
A class can contain an object of itself, but you can't instantiate that object in constructor or at the time of declaration. This will cause infinite recursion and StackOverflow
exception.
You can have a separate method to instantiate like:
class Class1
{
public int test1 { get; set; }
private Class1 x;
public void CreateClass1()
{
x = new Class1();
}
}
and then call it like:
Class1 obj = new Class1();
obj.CreateClass1();
Upvotes: 5
Reputation: 152501
Class1
creates a Class1
, which creates another Class1
, which creates another Class1
, which ...
So each constructor call gets added to the execution stack until it overflows.
Since you don't specify what you want to do with the instance there's no way to know what the right answer is.
For good geek humor, Google recursion
Upvotes: 13
Reputation: 25370
It's pretty straightforward, your problem is every time you create a Class1
, that object creates its own Class1
. Hence, you're going to recurse until you blow up.
You can debug it and watch what happens. Set a breakpoint within Class1
somewhere and watch it get hit over and over.
Upvotes: 5