Home >Backend Development >C++ >How Does C# Achieve Functionality Similar to C 's 'friend' Keyword?

How Does C# Achieve Functionality Similar to C 's 'friend' Keyword?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-29 17:24:18576browse

How Does C# Achieve Functionality Similar to C  's

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:

  • Only internal members are exposed, not private members.
  • It can only be used for assemblies, not classes.
  • It does not grant access to inherited private members.
  • It is intended for testing purposes only and should not be used for other scenarios.

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!

Statement:
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