Home > Backend Development > C++ > How Does C# Achieve Functionality Similar to C 's 'Friend' Keyword for Controlled Access to Private Members?

How Does C# Achieve Functionality Similar to C 's 'Friend' Keyword for Controlled Access to Private Members?

Susan Sarandon
Release: 2024-12-28 18:46:10
Original
935 people have browsed it

How Does C# Achieve Functionality Similar to C  's

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")]
Copy after login

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:

  • It requires explicit declaration in AssemblyInfo.cs.
  • It applies to assemblies rather than individual classes.
  • It does not enable access to all private members; it only grants access to internal members.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template