Constructor call within a constructor

  • Thread starter Thread starter Greg
  • Start date Start date
G

Greg

Is it possible to call a constructor from within a
constructor

I mean

Class A
{
public A(string getModifiedVal)
{
.........
}
}

Class B
{
public B()
{
//Do some processing to get modifiedValue

A(modifiedValue); // I know this doesn't work
//but is there a way to do it
}
}
 
A constructor always constructs an object. In the constructor for B, you
could do this

public B()
{
A obj=new A(modifiedValue);
}

If you don't want an A-object you should put the actual functionality into
a static method:

Class A
{
public A(string getModifiedVal)
{
DoSomething(getModifiedVal);
}

public static void DoSomething(string val)
{
//action
}
}

Class B
{
public B()
{
//Do some processing to get modifiedValue

A.DoSomething(modifiedValue);
}
}

/Hugo
 
A derived class call always the base class constructor, if you don't specify
a constructor the base() constructor is called
The base constructor is called always as first, than is executed the code in
the constructor class.

Class A
{
public A(string s){ ...} //Call Object() constructor
}

Class B: A
{
public B() {} //Call A() that in is this case is Obejct()

public B(string s):base(s){ ... } //Call A(string s)
}
 
Hi,


Hugo Wetterberg said:
A constructor always constructs an object. In the constructor for B, you
could do this

public B()
{
A obj=new A(modifiedValue);
}

This will create a new instance of A local to the constructor of B, this has
nothing to do with the original post, it does not contribute to the
construction of B.

Regarding the original post.
It will not work that way, You have two options though.

If the modifications of the parameter does not imply calling a method of B
you can do so in the constructor like this:

public B( string c): base( c.SubString( 1,2 ) )
{}

if the string used in A is generated by some method in B you CANNOT do
something like:

public B( string c): base( MethodOfB( ) ) {}

if MethodOfB is an instance member cause B is not yet build.

But you can do that if MethodOfB is static :

public B( string c): base( MethodOfB( ) ) {}

static string MethodOfB() { return "test";}


Jon:

Maybe this is a good addition to your contructor page.


Hope this help,
 
Back
Top