Question about inheritance

  • Thread starter Thread starter Du Dang
  • Start date Start date
D

Du Dang

class Base
{
public Base (string str)
{
Console.WriteLine(str);
}
}

class Derived : Base
{
public Derived (int i)
{
// do some thing here based on "i" to generate a
string
base ("some string"); <- this does work
}
}

==================

// i know something like this would work .. but this is not what i need
public Derived (string msg) : base (msg) {
}

thanks for any suggestion
 
The very first statement in the body of a constructor is always the call to
the base class.
There can not be any other statements before a base(foo,...) call.

To work around this limitation, create a separate method that does something
(in your case, Console.WriteLine(str); ) and call this method from your base
and derived constructors.
 
"Du Dang" ...
class Base
{
public Base (string str)
{
Console.WriteLine(str);
}
}

class Derived : Base
{
public Derived (int i)
{
// do some thing here based
// on "i" to generate a string

base ("some string");
}
}

==================

// i know something like this would work ..
// but this is not what i need
public Derived (string msg) : base (msg) {
}

As many others has said, nothing can proceed the call to the base
constructor within a constructor in a devived class.

There is however a solution, which could or could not work for you,
depending on how you want to convert the int to a string.

class Base
{
public Base(string str)
{
Console.WriteLine(str);
}
}

class Derived : Base
{
public Derived (int i) : base(ConvertingMethod(i))
{
}

static string ConvertingMethod(int i)
{
// Do some converting...
return "X" + i;
}
}

NB! The converting method has to be static, as you can't reach any instance
attributes, methods or properties until the base constructor has finished...

// Bjorn A
 
Thanks to Joe, Oleg and Bjorn for helping out.

I think this would do the trick.

Thank again,

Du Dang
 
Back
Top