Friend Keyword in C#
In object-oriented programming, the "friend" keyword provides controlled access to private class members to certain classes. While C offers the "friend" keyword, C# lacks a direct equivalent for this feature.
Alternative: InternalsVisibleTo
C# utilizes the InternalsVisibleTo attribute to achieve limited access to private members, primarily for testing purposes. This attribute designates assemblies or namespaces as trusted, allowing them to access internal members that are otherwise hidden from external code.
Example
Consider the following example in AssemblyInfo.cs:
[assembly: InternalsVisibleTo("OtherAssembly")]
This attribute makes the assembly accessible to the "OtherAssembly." Any methods or properties marked as internal within the assembly can now be accessed from the "OtherAssembly."
Usage in Testing
The InternalsVisibleTo attribute proves particularly useful in unit testing scenarios. By marking an assembly as InternalsVisibleTo to the test assembly, private members become accessible for testing purposes while remaining hidden from other external code.
Considerations
While InternalsVisibleTo provides a mechanism for controlled access, it differs from the C "friend" keyword in several ways:
The above is the detailed content of How Does C# Achieve Functionality Similar to C 's 'Friend' Keyword for Controlled Access to Private Members?. For more information, please follow other related articles on the PHP Chinese website!