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
!