Christian Sauer
Christian Sauer

Reputation: 10899

Interface does not behave like an Object?

I have a little problem with an interface. A bunch of my classes implement the ILayoutObject interface. A method declares a variable as ILayoutObject (defaulting it as Nothing) and then runs some code which decides which object it should be. The problem is, the evaluation code runs in a method which receives the variable as a parameter and assigns an object to it. With objects, this would be no problem. The object would be affected by the changes in the method and everything would be OK. Howeverm, when using an interface, the variable in the calling code remains Nothing and behaves like a normal variable. Does anyone have any ideas on how to circumvent that? Alas, due to code structure I am unable to use ByRef or functions :(

Here is some code:

Protected LayoutHandler As Dictionary(Of String, Action(Of Constants.OptionsEntryStructure, ILayoutElements)) = New Dictionary(Of String, Action(Of Constants.OptionsEntryStructure, ILayoutElements)) From
    {
    {Constants.KeyLayoutType, AddressOf KeyLayoutType}
    }

Sub MakeLayOuts
    Dim LayoutElement As ILayoutElements = Nothing 
    Dim Value = "SomeValues"
    Dim key = "Key"
    LayoutHandler(key)(Value, LayoutElement)
    ' LayoutElement remains nothing.....
End Sub

Protected Sub KeyLayoutType(elem As Constants.OptionsEntryStructure, Layout As ILayoutElements)
    Layout = New LayoutObject 'which would implement the interface
End Sub

Upvotes: 0

Views: 73

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

You need to declare the parameter as ByRef if you want to alter the object to which the variable in the calling code points to:

Protected Sub KeyLayoutType(elem As Constants.OptionsEntryStructure, ByRef Layout As ILayoutElements)
    Layout = New LayoutObject 'which would implement the interface
End Sub

This is true with any reference type (classes). The fact that they are referenced with an interface makes no difference.

If you can't use ByRef, and you can't use a function to return the new object, then your only other real option would be to request a type of object which has the layout object as a property. For instance:

Public Interface ILayoutElementContainer
    Public Property LayoutElement As ILayoutElements
End Interface

Protected Sub KeyLayoutType(elem As Constants.OptionsEntryStructure, Container As ILayoutElementContainer)
    Container.LayoutElement = New LayoutObject 'which would implement the interface
End Sub

Upvotes: 1

Related Questions