fork download
  1. using System;
  2.  
  3. namespace Test
  4. {
  5. public class A
  6. {
  7. public string Info { get; set; }
  8. /* much more data */
  9. }
  10.  
  11. public class B
  12. {
  13. private A m_instanceOfA;
  14.  
  15. public B(A a) { m_instanceOfA = a; }
  16.  
  17. public string Info
  18. {
  19. get { return m_instanceOfA.Info; }
  20. set { m_instanceOfA.Info = value; }
  21. }
  22.  
  23. // requires an instance of a private object, this establishes our pseudo-friendship
  24. internal A GetInstanceOfA(C.AGetter getter) { return getter.Get(m_instanceOfA); }
  25.  
  26. /* And some more data of its own*/
  27. }
  28.  
  29. public class C
  30. {
  31. private A m_instanceOfA;
  32.  
  33. private static AGetter m_AGetter; // initialized before first use; not visible outside of C
  34.  
  35. // class needs to be visible to B, actual instance does not (we call b.GetInstanceOfA from C)
  36. internal class AGetter
  37. {
  38. static AGetter() { m_AGetter = new AGetter(); } // initialize singleton
  39.  
  40. private AGetter() { } // disallow instantiation except our private singleton in C
  41.  
  42. public A Get(A a) { return a; } // force a NullReferenceException if calling b.GetInstanceOfA(null)
  43. }
  44.  
  45. static C()
  46. {
  47. // ensure that m_AGetter is initialized
  48. System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(AGetter).TypeHandle);
  49. }
  50.  
  51. public C(B b)
  52. {
  53. m_instanceOfA = b.GetInstanceOfA(m_AGetter);
  54. }
  55.  
  56. public string Info
  57. {
  58. get { return m_instanceOfA.Info; }
  59. set { m_instanceOfA.Info = value; }
  60. }
  61.  
  62. /* And some more data of its own*/
  63. }
  64.  
  65. public class Test
  66. {
  67. public static void Main()
  68. {
  69. A a = new A();
  70. B b = new B(a);
  71. C c = new C(b);
  72. c.Info = "Hello World!";
  73. Console.WriteLine(a.Info);
  74. }
  75. }
  76. }
Success #stdin #stdout 0.01s 131648KB
stdin
Standard input is empty
stdout
Hello World!