Groups | Blog | Home
all groups > c# > february 2004 >

c# : Question about inheritance


Du Dang
2/28/2004 8:54:58 PM
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


Oleg Ogurok
2/28/2004 11:30:14 PM

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.



[quoted text, click to view]

Bjorn Abelli
2/29/2004 11:48:32 AM

"Du Dang" ...

[quoted text, click to view]

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

Du Dang
2/29/2004 11:52:55 AM
Thanks to Joe, Oleg and Bjorn for helping out.

I think this would do the trick.

Thank again,

Du Dang


[quoted text, click to view]

AddThis Social Bookmark Button