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

How Does C# Achieve the Functionality of C 's 'friend' Keyword for Controlled Access to Private Members?

Barbara Streisand
Barbara StreisandOriginal
2024-12-27 06:41:09904browse

How Does C# Achieve the Functionality of C  's

Friend in C and its Absence in C#

In C , the "friend" keyword grants access to private members of a class to external classes. This allows for controlled sharing of private information without compromising encapsulation. However, this concept is not directly implemented in C#.

Bridging the Gap: InternalsVisibleTo

C# offers an attribute called InternalsVisibleTo as the closest approximation to "friend." It allows an assembly to access the internal members (including private members) of another assembly. This provides a limited form of controlled access.

Consider the following scenario:

  • You have a class named ClassA with private members.
  • You want a test class, Tester, to access these private members.

To achieve this, you would place the following attribute in the AssemblyInfo.cs file of ClassA:

[assembly: InternalsVisibleTo("TesterAssembly")]

Replace "TesterAssembly" with the name of the assembly containing the Tester class. By doing so, you are granting TesterAssembly access to the internal members of ClassA.

Example Usage

To illustrate how this works, here is a simple example:

ClassA.cs

public class ClassA
{
    private int _privateMember;

    public int PublicMember { get; set; }
}

Tester.cs

using ClassAAssembly;

public class Tester
{
    public void Test()
    {
        // Access private member through InternalsVisibleTo
        var instance = new ClassA();
        instance._privateMember = 10;
    }
}

By applying the InternalsVisibleTo attribute, you can control the accessibility of internal members (even private members) on an assembly level, enabling managed code testing without exposing sensitive data to external consumers.

The above is the detailed content of How Does C# Achieve the Functionality of C 's 'friend' Keyword for Controlled Access to Private Members?. 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