B
Brad
Question for all: Would one consider this a loophole in .net with respect
to nested (inner) classes?
1) Create outer class Foo and create a nested class Yin (inside Foo's class
definition ofcourse).
2) Let Foo have non-static protected (or public) method Bar() and Yin have a
non-static method called Yang().
4) Add a member object to Foo of Class Yin called yinObj.
5) Create an Object of Class Foo called fooObj.
Now if try to access from Foo's method Bar() from yinObj's (Yin's) method
Yang(), Visual Studio .Net compiler will correctly generate the error:
Cannot access a non-static member of outer type 'Foo' via nested type
'Foo\Yin'
However, I can get around this by creating a delegate BarWrapper which
serves as a wrapper function. All I do is the following:
A) Define Delegate BarWrapper from the scope of the outer class as public
delegate void BarWrapper.
B) Create instance of BarWrapper called BarWrap as a public member of nested
Class Yin.
C) Wrap Bar inside BarWrap in the Constructor of Foo as follows:
yinObj.BarWrap = new BarWrapper (Bar).
D) Place a call to BarWrap from within Yin's Method Yang as follows: Yang()
{ BarWrap(); }
Now when I compile, I will NOT get an error from the compiler. In effect I
have successfully accessed the non-static member function Bar from the
nested Class Yin.
Its as if I accomplished something the language was intending to prevent.
Is this a loophole in the language (as a result of the Delegate construct)
or is the ability to do what I did above intended?
Thanks,
Brad
to nested (inner) classes?
1) Create outer class Foo and create a nested class Yin (inside Foo's class
definition ofcourse).
2) Let Foo have non-static protected (or public) method Bar() and Yin have a
non-static method called Yang().
4) Add a member object to Foo of Class Yin called yinObj.
5) Create an Object of Class Foo called fooObj.
Now if try to access from Foo's method Bar() from yinObj's (Yin's) method
Yang(), Visual Studio .Net compiler will correctly generate the error:
Cannot access a non-static member of outer type 'Foo' via nested type
'Foo\Yin'
However, I can get around this by creating a delegate BarWrapper which
serves as a wrapper function. All I do is the following:
A) Define Delegate BarWrapper from the scope of the outer class as public
delegate void BarWrapper.
B) Create instance of BarWrapper called BarWrap as a public member of nested
Class Yin.
C) Wrap Bar inside BarWrap in the Constructor of Foo as follows:
yinObj.BarWrap = new BarWrapper (Bar).
D) Place a call to BarWrap from within Yin's Method Yang as follows: Yang()
{ BarWrap(); }
Now when I compile, I will NOT get an error from the compiler. In effect I
have successfully accessed the non-static member function Bar from the
nested Class Yin.
Its as if I accomplished something the language was intending to prevent.
Is this a loophole in the language (as a result of the Delegate construct)
or is the ability to do what I did above intended?
Thanks,
Brad