214

Possible Duplicate:
Why does C# not provide the C++ style ‘friend’ keyword?

I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.

In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example?

5
  • 3
    You shouldn't test private members directly like if they were accessible as public. Usually, people test against Public members only: stackoverflow.com/a/5662371/62921 Private members would be tested along the way indirectly.
    – ForceMagic
    Jun 21, 2013 at 14:09
  • 5
    This is not a duplicate. The other question is asking why it is missing, not how to get around it.
    – DanielV
    Feb 6, 2019 at 4:38
  • 1
    For testing - use private accessor - stackoverflow.com/a/4052474/828062 For factory pattern - mark the method as internal or protected internal - docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…
    – zendu
    May 15, 2019 at 2:03
  • 1
    This is not a duplicate. The other question is "opinion-based" (which is why some mean-spirited people decided to close that other question). I don't know why unhelpful troglodytes decided to close this question - it is neither a duplicate, nor opinion based.
    – Ian Boyd
    Nov 14, 2021 at 16:23
  • @IanBoyd, "troglodyte" is a bit much. Be nice, please.
    – Chris
    Nov 15, 2021 at 21:19

5 Answers 5

288

There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!

Example: To be placed in AssemblyInfo.cs

[assembly: InternalsVisibleTo("OtherAssembly")]
8
  • 15
    Interesting note, in VB.NET Internal is still called Friend.
    – Jeff
    Oct 17, 2013 at 19:55
  • 1
    MSDN says: "All nonpublic types in an assembly are visible to another assembly" How ugly ! Who will ever use that nonsense? I prefer the answer from RobG.
    – Elmue
    Jan 22, 2014 at 18:52
  • 4
    @Elmue: MSDN is incorrect. Private nested types wouldn't be visible, for example. And the internal members are only visible to the specified assembly - it's not like it's just making everything public. I far prefer using this over reflection, which isn't refactoring-friendly or compile-time-checking-friendly.
    – Jon Skeet
    Jan 22, 2014 at 18:53
  • OK. Let's better say that both are ugly workarounds. The original question was an equivalent for friend classes. For me it is very weird that Microsoft did not implement that. I want one class have access to another class in the SAME assembly. What do I do ?
    – Elmue
    Jan 25, 2014 at 2:39
  • 3
    @Elmue: You make the class internal, that's all. Yes, it's less fine-grained than friend - which is useful in some cases, and less useful in others. Personally it doesn't bother me.
    – Jon Skeet
    Jan 25, 2014 at 8:00
102

The closet equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:

class Outer
{
    class Inner
    {
       // This class can access Outer's private members
    }
}

or if you prefer to put the Inner class in another file:

Outer.cs
partial class Outer
{
}


Inner.cs
partial class Outer
{
    class Inner
    {
       // This class can access Outer's private members
    }
}
13
  • 11
    Note that in order to access the outer class' members, unless the variable is static (or const), you still need a reference to the instance of Outer. As per the accepted answer here: stackoverflow.com/questions/3155172/…
    – Itison
    Jan 8, 2013 at 2:45
  • 3
    Doh! Extension methods are not allowed on an inner class.
    – Jess
    May 1, 2015 at 13:25
  • 2
    I find this an extremely interesting idea. If we can except the token "partial" keyword, then we can allow other classes (repository, factory, ...) to obtain access to our private members. What's more, that class is forced to make it blatently obvious that it is doing so (i.e. wrap itself in a partial of the class it is accessing).
    – Timo
    Feb 12, 2017 at 23:26
  • 1
    this is a correct answer but has wrong explanation. You would use Inner class in the outer class and hide from others, not the other way round. Feb 4, 2019 at 18:14
  • 1
    This is an old post, however I have a point to add. Totally agree with @CodeNameJack, you would use inner in the outer, however, this way access is not granted, and comiplation error arises when trying to access the variable of inner class. You have access from Inner class to Outer class private variables, but not the other way round (from Outer class to Inner private variables) which turns to be quite weird to me, but as far as I checked this is how it works. May 6, 2020 at 7:39
48

Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.

In C++, make the Factory a friend of Widget class.

In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.

This involves a fair amount of tedium - exposing all the naturally public properties again in the interface.

1
  • 2
    It's a good pattern to use, but not often a good solution when unit testing, because you need fine control over the construction of the class you're testing, which should be isolated from other dependencies. If my factory injected other concrete dependencies into the class I'm testing, I'd be in strife. Oct 9, 2019 at 21:58
16

There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.

Given a class with this definition:

public class Class1
{
    private int CallMe()
    {
        return 1;
    }
}

You can invoke it using this code:

Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);

int result = (int)callMeMethod.Invoke(c, null);

Console.WriteLine(result);

If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."

2
  • 4
    Reflection has heavy performance cost and oftenly leads to poorly readable code. The "partial outer class" approach is much better for me when it's an option.
    – AFract
    Jul 13, 2017 at 7:38
  • 4
    @AFract - as of .NET 4.5.1, Reflection was re-written and is no longer a performance concern. This used to be the case prior to 4.5.1. Unfortunately, the CLR Team did a poor job of communicating this fact. Try testing some heavy Reflection code compiled pre-4.5.1 and re-test the same exact code under .NET 4.5.1+. You will see a massive difference.
    – Dave Black
    Nov 15, 2019 at 23:10
7

You can simulate a friend access if the class that is given the right to access is inside another package and if the methods you are exposing are marked as internal or internal protected. You have to modify the assembly you want to share and add the following settings to AssemblyInfo.cs :

// Expose the internal members to the types in the My.Tester assembly
[assembly: InternalsVisibleTo("My.Tester, PublicKey=" +
"012700000480000094000000060200000024000052534131000400000100010091ab9" +
"ba23e07d4fb7404041ec4d81193cfa9d661e0e24bd2c03182e0e7fc75b265a092a3f8" +
"52c672895e55b95611684ea090e787497b0d11b902b1eccd9bc9ea3c9a56740ecda8e" +
"961c93c3960136eefcdf106955a4eb8fff2a97f66049cd0228854b24709c0c945b499" +
"413d29a2801a39d4c4c30bab653ebc8bf604f5840c88")]

The public key is optional, depending on your needs.

Not the answer you're looking for? Browse other questions tagged or ask your own question.