I have such a class. (This is just an example)
public class NewTest
{
public int I { get; set; }
public NewTest()
{
I = 10;
throw new ApplicationException("Not Possible");
}
}
Now, if I use a class like this
NewTest t = new NewTest();
In the above line, since the NewTest constructor throws an exception to the variable t, it never assigns any value, because until the constuctor completes, it throws an exception, but according to the test, and also for another question ( Why throw an exception in the constructor leads to the creation of a null reference? ) .
Now this object is created in Heap, but it does not contain any root variable for the link, so does this create a problem for garbage collection? or is it something memory leak?
The following example will help me clear my confusion. Another example
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
NewMethod();
System.GC.Collect();
Console.WriteLine("Completed");
Console.ReadLine();
}
private static void NewMethod()
{
Object obj = null;
try
{
Console.WriteLine("Press any key to continue");
Console.ReadLine();
NewTest t = new NewTest(out obj);
}
catch
{
Console.WriteLine("Exception thrown");
}
try
{
Console.WriteLine("Press any key to continue");
Console.ReadLine();
NewTest1 t = new NewTest1();
}
catch
{
Console.WriteLine("Exception thrown");
}
Console.WriteLine("Press any key to continue");
Console.ReadLine();
System.GC.Collect();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
}
public class NewTest1
{
public int I { get; set; }
public NewTest1()
{
I = 10;
throw new ApplicationException("Not Possible");
}
}
public class NewTest
{
public int I { get; set; }
public NewTest(out Object obj)
{
obj = this;
I = 10;
throw new ApplicationException("Not Possible");
}
}
}