Home >Backend Development >C++ >How Does C# Achieve Functionality Similar to C 's 'friend' Keyword?
Friend Keyword Equivalent in C#
In C , the "friend" keyword grants access to private members of a class to another class. In C#, there is no direct equivalent, but the "InternalsVisibleTo" attribute provides limited access for testing purposes.
Usage of "InternalsVisibleTo" Attribute
The "InternalsVisibleTo" attribute is placed in the AssemblyInfo.cs file within each assembly. It specifies which other assemblies are allowed to access its internal members, which includes private members.
Example
To allow the Tester class access to private members of another class:
// AssemblyInfo.cs [assembly: InternalsVisibleTo("TesterAssembly")]
Note that "TesterAssembly" must be the name of the assembly containing the Tester class.
Limitations
"InternalsVisibleTo" is not a true equivalent of the "friend" keyword and has several limitations:
The above is the detailed content of How Does C# Achieve Functionality Similar to C 's 'friend' Keyword?. For more information, please follow other related articles on the PHP Chinese website!