Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement multiple interfaces with a single property in VB.NET

On startup, I load all my app.config values into a class named ConfigValues. My database only needs some of them so I have an IDatabaseConfig interface that specifies just the parameters that it needs. That way, when I'm creating a database connection class, with constructor injection, I can require that it is passed anything that implements IDatabaseConfig.

What I'd like to do is declare multiple interfaces on the ConfigValues class and allow some of the properties to implement multiple contracts simultaneously.

Here's a small code example:

Public Interface IAppConfig
    Property Server As String
    Property ErrorPath As String
End Interface

Public Interface IDatabaseConfig
    Property Server As String
End Interface

Public Class ConfigValues
    Implements IAppConfig
    Implements IDatabaseConfig

    Public Property ErrorPath As String Implements IAppConfig.ErrorPath

    'need different syntax - does not compile:
    Public Property Server As String Implements IAppConfig.Server, 
                                     Implements IDatabaseConfig.Server

End Class

In VB.NET, is there a way to specify that a single property satisfies the contract for multiple interfaces?

This is the exact opposite of these two questions on SO, which are trying to split up the same interface name into two different properties.

  • Implementing 2 Interfaces with 'Same Name' Properties
  • How to implement an interface in VB.Net when two methods have the same name but different parameters

As a cludgy workaround, I could have both properties refer to the same backing property, but I'd have to change the property name on at least one of them, which changes the API.

Private _server As String
Public Property ServerForApp As String Implements IAppConfig.Server
    Get
        Return _server
    End Get
    Set(value As String)
        _server = value
    End Set
End Property
Public Property ServerForDatabase As String Implements IDatabaseConfig.Server
    Get
        Return _server
    End Get
    Set(value As String)
        _server = value
    End Set
End Property
like image 737
KyleMit Avatar asked Feb 07 '14 18:02

KyleMit


1 Answers

I think what you want is supported, you just got the syntax wrong:

Public Class ConfigValues
    Implements IAppConfig
    Implements IDatabaseConfig

    Public Property ErrorPath As String Implements IAppConfig.ErrorPath

    Public Property Server As String Implements IAppConfig.Server, 
                                                IDatabaseConfig.Server

End Class
like image 175
SWeko Avatar answered Sep 27 '22 20:09

SWeko