Inner Class Extends Outer Class

  • Thread starter Thread starter Martijn Mulder
  • Start date Start date
M

Martijn Mulder

A construction like this:

class Outer
{
class Inner:Outer
{
}
}

compiles without problem but does it introduce infinity?
 
I've never thought of doing this! However, it seems to work OK.

public class Outer
{
public class Inner : Outer
{
public override string ToString()
{
return "I'm an inner";
}
}

public override string ToString()
{
return "I'm an outer";
}
}


To test it:

static void Main(string[] args)
{
Outer o = new Outer();
Console.WriteLine(o);

Outer.Inner i = new Outer.Inner();
Console.WriteLine(i);

Console.WriteLine("\nPress ENTER to continue");
Console.ReadLine();
}


Without using 'using' statements you have to refer to it as Outer.Inner
so it's a bit long winded! I'd prefer to declare them sequentially for
ease of readability but it seems that the compiler can cope with it OK.
 
Hi Martjin,

Why would you think that it might "introduce infinity"?

After all, it's not like you are asking about something recursive, like this:

class Outer : Inner { }
class Inner : Outer { }

BTW, the above fails during compilation with an interesting message:

Error 2 Circular base class dependency involving 'Inner' and 'Outer'
 
Why would you think that it might "introduce infinity"?
After all, it's not like you are asking about something recursive, like
this:

class Outer : Inner { }
class Inner : Outer { }

BTW, the above fails during compilation with an interesting message:

Error 2 Circular base class dependency involving 'Inner' and 'Outer'



I can compile and run this program without problems. But I don't see any use
for it (yet):

//class Outer
public class Outer
{

//ToString
public override string ToString(){return "Outer class";}


//nested class Inner
public class Inner:Outer
{

//ToString
public override string ToString(){return "Inner class";}
}


//Main
static void Main()
{
System.Console.WriteLine(new Outer());
System.Console.WriteLine(new Outer.Inner());
System.Console.WriteLine(new Outer.Inner.Inner());
System.Console.WriteLine(new Outer.Inner.Inner.Inner());
}
}

_____________________
output:

Outer class
Inner class
Inner class
Inner class
 
Hi Martjin,

Yes, I suspect that it would work - I don't see why anyone would think that it
wouldn't. I don't know of any good use for it either ;)
 

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

Back
Top