0

I am trying to program an interesting trick I believe I once saw in a Java program, and possibly in some C# code.

I have a static method that takes an ID as an integer, looks it up in a table, then uses the information from that row to create and return an instance of that class. The thing is, I want to make a certain constructor visible only to my static function, and not to just anyone. I've looked over the modifies for various levels of protection, but cannot seem to locate any that might accomplish this task. Does anyone have any ideas how I might achieve this?

user978122
  • 5,531
  • 7
  • 33
  • 41
  • Please enlighten me of what the gain is from this :) – WozzeC Nov 22 '12 at 07:45
  • "Visibility" is relative. The Net Runtime can call the method, so you can call it via reflection. See here for example: http://stackoverflow.com/questions/135443/how-do-i-use-reflection-to-invoke-a-private-method-in-c – igrimpe Nov 22 '12 at 07:47

2 Answers2

2

Why not make the constructor private?

Public Class Foo
    Private Sub New ()
    End Sub

    Public Shared Function CreateFoo (bar As Integer) As Foo
        Return New Foo ()
    End Sub
End Class
Rolf Bjarne Kvinge
  • 19,253
  • 2
  • 42
  • 86
1

This would be a "quick fix" to this, but by no means exactly what you are looking for.

Create an inherited class with the constructor you need and then return the class in its base format. This would make the contructor "invisible" atleast as long as you are working with Derp

Public Class Herp
  Inherits Derp
    Public Sub New(ByVal Secret As String)
        _Secret = Secret
    End Sub
End Class

Public Class Derp
   Protected _Secret As String
   Public Sub New()

   End Sub
End Class

And then do this:

Public Shared Function GetDerp() As Derp
   Dim derp As Derp = New Herp("Secret")
   Return Derp
End Function
WozzeC
  • 2,630
  • 1
  • 13
  • 12