Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private-ish method?

Within my projects I often want to have a method (or function if you prefer) that is private, however I also want to access it from ONE other class. Is this a possibility?

To clarify, this method can be accessed from ClassA, its own class but not any other.

like image 715
Zac Shepherd Avatar asked Dec 25 '15 09:12

Zac Shepherd


2 Answers

There are plenty of ways to do this untill your last statement that is "and ONLY that class", i can only think of 1 way to do that and it is to have the classes laid out in assemblies as such as such:

Assembly A only contains class A with the method you want declared as internal

Assembly B declared as a friendly assembly : https://msdn.microsoft.com/en-us/library/0tke9fxk.aspx and contains code to call A (it can as to it it is internal as if in the same assembly as it is a friend assembly)

No other assembly linked to A , B or both will be able to call the method on class A as it is internal.

like image 112
Ronan Thibaudau Avatar answered Oct 14 '22 14:10

Ronan Thibaudau


The best way that I can think of is this.

In C# 5, a set of caller information attributes were added, namely [System.Runtime.CompilerServices.CallerMemberName], [System.Runtime.CompilerServices.CallerFilePath], and [System.Runtime.CompilerServices.CallerLineNumber]. We can use the CallerFilePathAttribute to see whether the caller comes from a particular .cs file.

Usually, one file will only contain one class or struct. For example, ClassA is defined in ClassA.cs. You can check if the caller file name matches ClassA.cs in the method.

So modify your method's parameters like this:

([CallerFilePath] string callerFilePath = "" /*Other parameters*/)

In the method, check if the callerFilePath matches the file path of ClassA. If it does not, throw an exception saying that the method can only be accessed from ClassA!

like image 45
Sweeper Avatar answered Oct 14 '22 12:10

Sweeper