Also available at

Also available at my website http://tosh.me/ and on Twitter @toshafanasiev

Thursday, 21 November 2013

C++ friends for C#

A mate of mine asked me about C++ style 'friends' for C# and I thought I'd lay out the nearest approximation I could make to this C++ language feature in C#.

On the face of it it may look as though this sort of feature just makes it easy for you to violate encapsulation in your code but on closer inspection it's a perfectly valid way of compartmentalising different aspects of one logical unit of code into a set of related classes. To be honest though, I didn't really want to get into that here.

What I wanted to get across is that you can achieve the same effect in C# as declaring a friend in C++, with the help of nested types and partial classes:

public partial class MasterCounter
{
  public int Count { get; private set; }

  public Counter CreateCounter()
  {
    return new Counter(this);
  }

  public partial class Counter { }
}

// and then in a separate file ...

partial class MasterCounter
{
  partial class Counter
  {
    private readonly MasterCounter master;

    public Counter(MasterCounter master)
    {
      this.master = master;
    }

    public void Click()
    {
      master.Counter += 1;     
    }
  }
}

Having to nest the 'friend' class and make both classes partial are not the greatest compromises and you don't even have to do the latter if both class definitions fit comfortably in the same file - arguably having access to the same private state makes them, logically, parts of the same class. If you squint a bit you sort of can't see the declaration of the enclosing class in the second file.

Anyway, not rocket science, but interesting all the same.


No comments:

Post a Comment