there is class A having class B(nested) in it . now i require to use class A's functionality again in B . is there any optimised way to implement this thing.?
eg.
class A
{
class B
{
// have to re-implement class A here,...
}
}
there is class A having class B(nested) in it . now i require to use class A's functionality again in B . is there any optimised way to implement this thing.?
eg.
class A
{
class B
{
// have to re-implement class A here,...
}
}
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
navjot chandiPosted Sep 18, 2008, 12:50 AM
Posted Sep 17, 2008, 6:14 PM
Thank you
AlanPosted Sep 17, 2008, 5:15 PM
Nested classes are treated as static members of the containing class.
So to access the nested class B in class A, the syntax is A.B.
'b' is then declared as a variable of that type and is assigned a new object in which the variable 'a' , containing a reference to an instance of A, is passed to the constructor.
Posted Sep 17, 2008, 4:59 PM
How to explain the code A.B b = new A.B(a); in the above program?
AlanPosted Sep 17, 2008, 9:45 AM
If by 'reimplement A', you mean get access to A's instance members within the nested class B, then the usual way is to pass an A reference to B's constructor. For example:
using System;
class Test
{
static void Main()
{
A a = new A();
A.B b = new A.B(a);
Console.ReadLine();
}
}
class A
{
private void AMethod()
{
Console.WriteLine("Hello from AMethod");
}
internal class B
{
A a;
internal B(A a)
{
this.a = a;
BMethod();
}
private void BMethod()
{
Console.WriteLine("Hello from BMethod");
a.AMethod();
}
}
}
Notice that B even has access to A's private members.
Ryan AlfordPosted Sep 17, 2008, 8:44 AM
{
}
class B : A
{
}
it's called inheritance.