Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# have the equivalent of Delphi's private modifier

Tags:

c#

In Delphi, the private modifier is likely unique:

Contoso = class
private
   procedure DoStuff();
end;

you would think has the C# equivalent of:

class Contoso
{
   private void DoStuff()
   {
   }
}

But in Delphi, the private keyword is more unit friend. In other words, other classes in the same code file can access private members. Transcoding Delphi to C#, it would be the equivalent of the following code working:

public class Contoso
{
   private void DoStuff()
   {
   }
}

internal class Fabrikam
{
   Contoso _contoso;

   //constructor
   Fabrikam()
   {
      _contoso = new Contoso();
      _contoso.DoStuff(); //i can call a private method of another class
   }
}

Even though the method DoStuff is private to Contoso, other classes in the same file can call the method.

What i don't want is to make the method internal:

class Contoso
{
   internal void DoStuff();
}

because then other code in the assembly can see or call the DoStuff method; which i don't want.


Does C# support some sort of unit friend or unit internal access modifier?

like image 790
Ian Boyd Avatar asked Aug 15 '13 21:08

Ian Boyd


1 Answers

Not exactly.

In C# you can declare a member as internal , which gives classes (code) in the same assembly access to that member. This has more or less the same usage as Delphi's Unit access rule.

The scope is wider but you have more control.

You specifically state you don't want this, but think about the use cases. In Delphi you are unwillingly giving access to all private members. And you are prevented from putting each class in its own Unit.

In .NET, an assembly is 1 project and managing unwanted acces inside one assembly is easy. Putting up a fence to the rest of the world is much more important.

You cannot limit on a file boundary because a file has almost no significance in C#. A file boundary is not present in IL, and a rule like that could conflict with partial classes for one thing.

like image 99
Henk Holterman Avatar answered Sep 24 '22 00:09

Henk Holterman