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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Ryan AlfordRank #1,411 · 1.2K reputationPosted Sep 17, 2008, 4:44 AM EDT
{
}
class B : A
{
}
it's called inheritance.
AlanRank #669 · 3.6K reputationPosted Sep 17, 2008, 5:45 AM EDT
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.
Posted Sep 17, 2008, 12:59 PM EDT
How to explain the code A.B b = new A.B(a); in the above program?
AlanRank #669 · 3.6K reputationPosted Sep 17, 2008, 1:15 PM EDT
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, 2:14 PM EDT
Thank you
navjot chandi7 reputationPosted Sep 17, 2008, 8:50 PM EDT