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.
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.
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
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With