What makes it possible to create a instance of class inside of the class itself?
public class My_Class
{
My_Class new_class= new My_Class();
}
Other responses have mostly covered the question. If it helps wrap a brain around it, how about an example?
The chicken-and-egg problem is resolved as any recursive problem is: the basis case which doesn't keep producing more work / instances / whatever.
Imagine you've put together a class to automatically handle cross-thread event invocation when necessary. Heavily relevant for threaded WinForms. Then you'd like the class to expose an event which occurs whenever something registers or unregisters with the handler, and naturally it should handle cross-thread invocation as well.
You could write the code that handles it twice, once for the event itself and once for the status event, or write once and re-use.
The majority of the class has been trimmed out as it isn't really relevant to the discussion.
public sealed class AutoInvokingEvent
{
private AutoInvokingEvent _statuschanged;
public event EventHandler StatusChanged
{
add
{
_statuschanged.Register(value);
}
remove
{
_statuschanged.Unregister(value);
}
}
private void OnStatusChanged()
{
if (_statuschanged == null) return;
_statuschanged.OnEvent(this, EventArgs.Empty);
}
private AutoInvokingEvent()
{
//basis case what doesn't allocate the event
}
///
/// Creates a new instance of the AutoInvokingEvent.
///
/// If true, the AutoInvokingEvent will generate events which can be used to inform components of its status.
public AutoInvokingEvent(bool statusevent)
{
if (statusevent) _statuschanged = new AutoInvokingEvent();
}
public void Register(Delegate value)
{
//mess what registers event
OnStatusChanged();
}
public void Unregister(Delegate value)
{
//mess what unregisters event
OnStatusChanged();
}
public void OnEvent(params object[] args)
{
//mess what calls event handlers
}
}