Skip to main content
gamedev.net
🔒 Locked

C# Constructor Exiting

Started by ISOPimp Dec 20, 2002 at 3:02 PM 4 replies 1.2k views
Original Post
ISOPimp
ISOPimp
Is it possible to break out of a constructor and kill the instance it is constucting? example:
  class MyForm: public Form
{
	public MyForm()
	{
		if(true)
		{
			//Exit constructor somehow and quit program

		}
		else
		{
			InitializeComponent();
		}
		Console.WriteLine("I shouldnt see this");
	}
	static void Main() 
	{
		Application.Run(new MyForm());
	}
}
  
Arild Fines
Arild Fines
Throw an exception. The instance will not be constructed and any allocated memory will be left for garbage collection.



For those who believe in God, most of the big questions are answered. But for those of us who can''t readily accept the God formula, the big answers don''t remain stone- written. We adjust to new conditions and discoveries. We are pliable. Love need not be a command or faith a dictum. I am my own God. We are here to unlearn the teachings of the church, state, and our educational system. We are here to drink beer. We are here to kill war. We are here to laugh at the odds and live our lives so well that Death will tremble to take us -- Charles Bukowski
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
Arild Fines
Arild Fines
Ponder this:

  
using System;

namespace ConsoleApplication2
{
/// <summary>

/// Summary description for Class1.

/// </summary>

class Class1
{
public Class1()
{
throw new Exception();
}

public void Foo()
{
Console.WriteLine( "Foo" );
}
[STAThread]
static void Main(string[] args)
{
Class1 bleh = null;
try
{
bleh = new Class1();
}
catch( Exception )
{
}
bleh.Foo(); //NullReferenceException thrown here

}
}
}
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
Arild Fines
Arild Fines
Note to all: Posted source that uses tabs instead of spaces looks hideous in certain browsers.
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
ISOPimp
ISOPimp
Thanks guys, ill try throwing an exception.

Arild Fines: I''ll remember that for next time

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.