Question

I would like to organize a class as follows (pseudocode)

Class MyClass

  sub New(MethodEnabled as integer)

   if MethodEnabled = 0
       make MyMethod() to be Sub0()
   else
       make MyMethod() to be Sub1()
   end if

  end sub


  sub MyMethod()
     invoke(either sub0  or sub1 depending on "MethodEnabled" value)
  end sub 


  sub Sub0()
    some code here
  end sub

  sub Sub1()
    some code here
  end sub

End Class

What I wish is to have the sub "MyMethod()" to invoke (or "to be") either Sub0() or Sub1(), depending on how the class was constructed (either with MethodEnabled=0, or MethodEnabled=1).

I gather intuitively that I can do that by using delegates and invoke, but I am not much clear on how to actually do it, in practice.

Can anybody show me how I can possibly do this in the most elegant way. C# of VB.NET examples would be equally great. Thank you!

Was it helpful?

Solution

You need to either declare a delegate type or use System.Action, and then use an instance of that delegate type:

Class [MyClass]

    Private Delegate Sub myDelegate()
    Private myDelegateInstance As myDelegate
    'or you could just leave out 'myDelegate' and use 'System.Action'

    Sub New(ByVal MethodEnabled As Integer)

        If MethodEnabled = 0 Then
            myDelegateInstance = AddressOf Sub0
        Else
            myDelegateInstance = AddressOf Sub1
        End If

    End Sub

    Sub MyMethod()
        myDelegateInstance()
    End Sub

    Sub Sub0()
        'some code here
    End Sub

    Sub Sub1()
        'some code here
    End Sub

End Class
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top