For example, there are 2 classes:

class A{ BB; } class B{ string Name; } 

Is it possible to make it so that class A has the full right to change the value of B, while the user outside can only read it?

  • one
    So you want a friendly class equivalent for C #? There are no direct analogues, but perhaps you are satisfied with the access modifier internal , which allows you to access a member (method or variable) only from the same assembly. - Alexey Sarovsky
  • Yes, like a friendly class that has full access to some member of another class, however, a user from outside can only read it. - User100500
  • In its pure form, this is not. Try using internal, and it is probably better to revise the project, because it is somewhat counter-natural) - Alexey Sarovsky
  • Related question: Stackoverflow.com/q/774073/218063 - Andrew NOP

1 answer 1

Yes, it is. Internal classes have similar functionality. Here is an example:

 public class Test { public int X { get; private set; } public class TestMutator { public static void Mutate(Test t) { t.X++; } } } 
 Test test = new Test(); Console.WriteLine(test.X); // 0 Test.TestMutator.Mutate(test); Console.WriteLine(test.X); // 1 

This feature is often used, for example, to implement the Iterator pattern. For example, the enumerator List<T> in the Microsoft implementation is defined internally, and has access to the _version private field.

For external classes, there is no such functionality, since access to the “internals” of a class is a violation of encapsulation.

  • It seems to be what is needed, but I don’t like the fact that the inner class needs to be addressed through the dot, that we make the names long. = ( - User100500
  • @ User100500: Well, use var , business! And let an instance of the inner class create an outer class, for example. - VladD