Bahadır KONU

There is a topic in C++ called friend classes. We don't usually prefer this but, can we let a class use private features of another in C#

Re: Visual C# Language Let a class use some private features of another class (Friend classes of C++)

Matthew Watson

Thankfully not. I always treated friend declarations with extreme prejudice in C++...

Friend declarations give extremely tight coupling, and usually indicate a design that needs some refactoring.




Re: Visual C# Language Let a class use some private features of another class (Friend classes of C++)

Peter Ritchie

About the closest you can get are Nested Classes; but they're not two-way. For example:

Code Snippet

using System;

public class Testing {
private int value;
private class Nest {
private Testing testing;
public Nest(Testing testing) {
this.testing = testing;
}
public void Method() {
testing.value = 1;
}
}
public int Value { get { return value; } }
}

public static void Main() {
Testing testing = new Testing();
testing.value = 1; // CS0122
}






Re: Visual C# Language Let a class use some private features of another class (Friend classes of C++)

olanmills

This is kind of a pain for unit testing. Sometimes, we make methods public just for unit testing when they really should be private. We could put the unit tests in nested classes, internals or have the unit test classes inherit from the classes they are testing, but that wouldn't be as organized as the way we do it now.

I agree that the friend modifier can be bad design or even dangerous, but in the case of unit testing, I think it would be perfect.





Re: Visual C# Language Let a class use some private features of another class (Friend classes of C++)

Thomas Danecker

There is one alternative: You can use reflection to invoke private methods (if the code has sufficient permissions).




Re: Visual C# Language Let a class use some private features of another class (Friend classes of C++)

Matthew Watson

For unit tests, you could consider using InternalsVisibleToAttribute, which does exactly what it says on the tin - allows you to use "Friend Assemblies" (but it is pretty fiddly to use!).

(It does NOT allow you to access someone else's privates, tho' Wink)