HilaB
HilaB

Reputation: 179

Faking derived class but calling the real constructor and ignoring base constructor

I have the following classes:

public class Base
{
    private int x;
    public Base(int _x) { x = _x; }
}
public class Derived : Base
{
    int y;
    public Derived(int _x,int _y) : base(_x) { y = _y; }
}

I want to create a fake 'Derived' object, but to call the original constructor and ignore the base constructor. How can I do that?

Upvotes: 2

Views: 226

Answers (2)

HilaB
HilaB

Reputation: 179

actually I found a solution. I investigated a little and found out that I can do it with Typemock:

Isolate.Fake.Instance<Derived(Members.CallOriginal,ConstructorWillBe.Called, BaseConstructorWillBe.Ignored);

It allowes me to create a fake object, call the original constructor and ignore the base constructor.

Upvotes: 1

InBetween
InBetween

Reputation: 32770

You can't. When instantiating a Derived object, a constructor of Base must run; after all, a Derived instance is also a Base, the logic of creating a Base must be executed somewhere in the process.

You might be confusing not calling the base constructor with the case where it is implicitly called for you; this happends when Base has an accesible default constructor:

public class Base
{
    private int x;
    public Base() { } //default constructor
    public Base(int _x) { x = _x; }
} 

Then this is legal:

public class Derived : Base
{
    int y;
    public Derived(int _y) { y = _y; } //no explicit base() needed.
}

But that's only because the compiler will add the implicit call for you. The real code is:

public class Derived : Base
{
    int y;
    public Derived(int _y) : base() { y = _y; }
}

This seems like an XY Problem. What are you really trying to do?

Upvotes: 0

Related Questions