Workaround for the lack of inherited constructors

G

Guest

OK, here's my latest workaround for the lack of inherited constructors...

It requires that the class have a parameterless (default) constructor and a
public virtual "Initialize" method (which returns its "this"). An instance
(in this case a Number) is constructed and initialized like so:

Number n = ((Number)((Number)
typeof(Number).GetConstructor(System.Type.EmptyTypes).Invoke(new
object[]{})).Initialize(1)) ;

Which is pretty ugly, but if one uses the C preprocessor to create a macro:

# define New(typ,...) ((typ)((typ)
typeof(typ).GetConstructor(System.Type.EmptyTypes).Invoke(new
object[]{})).Initialize(__VA_ARGS__))

It can be reduced to:

Number n = New ( Number , 1 ) ;

Example.................................................................................

namespace Template
{
public class Number
{
private long x = 0 ;

public virtual Number
Initialize
(
long Value
)
{
this.x = Value ;

return ( this ) ;
}

public long
Value
{
get
{
return ( this.x ) ;
}
}

public override string
ToString()
{
return ( this.x.ToString() ) ;
}
}

public class Hex : Number
{
public override string
ToString()
{
return ( Value.ToString ( "X" ) ) ;
}
}

public class Fraction : Number
{
private long y = 1 ;

public virtual Fraction
Initialize
(
long Num
,
long Den
)
{
base.Initialize ( Num ) ;

this.y = Den ;

return ( this ) ;
}

public override string
ToString()
{
return ( base.ToString() + "/" + this.y.ToString() ) ;
}
}

class Template
{
[System.STAThread]
static void
Main
(
string[] Args
)
{
Number n = New ( Number , 1 ) ;
Hex h = New ( Hex , 13 ) ; // Uses "inherited
constructor"
Fraction f = New ( Fraction , 2 , 3 ) ;
Fraction g = New ( Fraction , 2 ) ; // Uses "inherited
constructor"

System.Console.WriteLine ( n ) ;
System.Console.WriteLine ( h ) ;
System.Console.WriteLine ( f ) ;
System.Console.WriteLine ( g ) ;

return ;
}
}
}
 
B

Bruce Wood

This is called "pounding a square peg into a round hole with a
sledgehammer."

There comes a point at which the solution is considerably nastier and
uglier than the original problem. At that point it is usually best to
give up, accept the language as it is (including its faults), and work
with it in that spirit of acceptance rather than trying to turn it into
some other language.

I think you've reached that point.
 

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