What is the equivalent of a 'friend' keyword in C Sharp?
You can use the keyword access modifier
internal
to declare a type or type member as accessible to code in the same assembly only.You can use the
InternalsVisibleToAttribute
class defined inSystem.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.
No, "internal" is not the same as "friend" (at least the C++ 'friend')
friend specifies that this class is only accessible by ONE, particular class.
internal specifies that this class is accessible by ANY class in the assembly.
internal
is the C# equivalent of the VB.NETfriend
keyword, as you have guessed (as opposed to a replacement)Usage is as follows
internal void Function() {} internal Class Classname() {} internal int myInt; internal int MyProperty { get; set; }
It, basically, is an access modifier that stipulates that the accessibility of the class / function / variable / property marked as internal is as if it were public to the Assembly it is compiled in, and private to any other assemblies