Getting TargetInvocationException when calling a virtual function from a constructor

J

JP

Hi,

I am facing a strange problem, please take a look at the code below:

public SaveTree()
{
........
......
......//some code
Initranges()
}

protected virtual Initranges()
{
........//some code
.......
}

Somewhere else, i have a derived class:

public SaveSingleTree: SaveTree
{
.........
//constructor not being overridden
}

Now, when i do something like this:

SaveTree tree = new SaveSingleTree()

I get an exception with the following text:
'System.Reflection.TargetInvocationException' occurred in mscorlib.dl
Exception has been thrown by the target of an invocation.

i have a set of base class and derived class in which a protected
virtual function is being overridden by the derived class. This
function is called internally by the constructor of the base class and
the constructor is NOT being overridden by the derived class.

Anyone have any idea what am i doing wrong? can i invoke a virtual
function from inside a constructor?

Jaspinder
 
L

Larry Lard

JP said:
Hi,

I am facing a strange problem, please take a look at the code below:

It really helps us to help you if you post real code. Below is some
real code which is the result of me attempting to deduce what you
meant:

using System;

namespace ConsoleApplication4
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
SaveTree t = new SaveSingleTree();

Console.ReadLine();
}
}

public class SaveTree
{
public SaveTree()
{
//some code
Initranges();
}

protected virtual void Initranges()
{
//some code
}
}

public class SaveSingleTree: SaveTree
{
//constructor not being overridden
protected override void Initranges()
{
}
}
}
Now, when i do something like this:

SaveTree tree = new SaveSingleTree()

I get an exception with the following text:
'System.Reflection.TargetInvocationException' occurred in mscorlib.dl
Exception has been thrown by the target of an invocation.

i have a set of base class and derived class in which a protected
virtual function is being overridden by the derived class. This
function is called internally by the constructor of the base class and
the constructor is NOT being overridden by the derived class.

The code above matches this description and performs without error or
exception.
Anyone have any idea what am i doing wrong? can i invoke a virtual
function from inside a constructor?

Show us your code.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top