Ensure the propper calling class.

  • Thread starter Thread starter Ray Cassick \(Home\)
  • Start date Start date
R

Ray Cassick \(Home\)

I have several classes that has a public interface (nothing really different
there :) ).

1) I would like to ensure that some classes can only be instantiated by a
specific class type.

2) I would like to restrict some public methods from being called only
from another certain class type.

I was trying to figure out a way that I could do this with attributes but I
am coming up empty.

Any ideas?
 
One way to do this would be to have a custom permission(based on strong name or whatever other criteria) and in your class do a link demand to check that the caller has the required custom permission.

--
Regards,
Anand M
VB.NET MVP

http://www.dotnetindia.com
 
Ray Cassick (Home) said:
I have several classes that has a public interface (nothing really
different there :) ).

1) I would like to ensure that some classes can only be
instantiated by a specific class type.

Make the class a nested, private class, so only the outer class can create
instances. Implement a Public interface. Something like:

class outer
public interface i
end interface

private class inner
implements i
end class

public function GetI as I
end function
end class
2) I would like to restrict some public methods from being called
only from another certain class type.

Apart from the same solution as above, you could put the classes in the same
assembly and declare the methods as Friend. But, usually there are other
criteria to choose the classes for the same assembly, so the criteria might
be competing, that's why I wouldn't do it. Instead, my design rule is: As
soon as an object can be accessed, all methods are available. I don't see
why it depends on the object calling the public methods whether
encapsulation of the object is broken or not.


--
Armin

How to quote and why:
http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html
 
Ray,
In addition to the other comments. The "easiest" way to ensure that a class
can only be instantiated or used by a specific class is to put both classes
in their own Assembly (Class Library) then make the constructor (Sub New)
for the second class Friend. To restricting the methods called make those
methods Friend also.

' In a class library by themselves:
Public Class Class1

Public Function CreatesClass2() As Class2
Return New Class2
End Function

End Class

Public Class Class2

Friend Sub New()
End Sub

Friend Sub MethodForClass1()
End Sub

Public Sub MethodForEveryOne()
End Sub

End Class

' In a different assembly referencing the above assembly

Dim c1 As New Class1
Dim c2 As Class2 = c1.CreatesClass2()
c2.MethodForClass1() ' error
c2.MethodForEveryOne() ' succeeds

Hope this helps
Jay
 
Back
Top