What is the equivalent of a 'friend' keyword in C Sharp?

xarzu picture xarzu · Jan 15, 2009 · Viewed 49.9k times · Source

What is the equivalent of a 'friend' keyword in C Sharp?

How do I use the 'internal' keyword?

I have read that 'internal' keyword is a replacement for 'friend' in C#.

I am using a DLL in my C# project that I have the source code for and yet I do not want to modify the existing code. I have inherited the class and I can use my inherited class any way I want. The problem is that most of the code in the parent class has protected methods. Will using a friend somehow make it possible to access or call these protected methods?

Answer

jason picture jason · Jan 15, 2009
  1. You can use the keyword access modifier internal to declare a type or type member as accessible to code in the same assembly only.

  2. You can use the InternalsVisibleToAttribute class defined in System.Rutime.CompilerServices to declare a type as accessible to code in the same assembly or a specified assembly only.

You use the first as you use any other access modifier such as private. To wit:

internal class MyClass {
    ...
}

You use the second as follows:

[assembly:InternalsVisibleTo("MyFriendAssembly", PublicKey="...")]
internal class MyVisibleClass {
    ...
}

Both of these can rightly be considered the equivalent of friend in C#.

Methods that are protected are already available to derived classes.