Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign more than one interface to variable type

Tags:

.net

vb.net

I am trying to create some levels of abstraction for a hardware interface i am writing and was wondering if there is some way that i can assign more than one interface as a single variabletype

The only way that comes to mind is to make a abstract class that impliments IDisposable and IDataEndPoint and then use that as my variable type and the base for my endpoints

GoogleFu, Stack Overflow and MSDN havnt provided any other ideas

Cheers!

ie

Public Class A
  Impliments IDisposable

Public ReadOnly DataEndpoint as IDataEndpoint, IDisposable <---- something like this

Protected Overridable Sub Dispose(disposing as Boolean)
  if disposing then
    DataEndPoint.Dispose
  end if
End Sub
Public Sub Dispose() Impliments IDisposable.Dispose
  Dispose(True)
  GC.SuppressFinalize(Me)
End Sub
End Class
like image 740
Oriphinz Avatar asked May 20 '26 17:05

Oriphinz


2 Answers

Why not having a type DataEndoint that implements both interfaces and DirectCast the property to the required interface when needed?

Public Class DataEndpoint 
  Implements IDataEndpoint, IDisposable

  'Implementation ...

End Class

Public Class A
  Implements IDisposable

Public ReadOnly DataEndpoint as DataEndpoint

Protected Overridable Sub Dispose(disposing as Boolean)
  if disposing then
    DirectCast(DataEndPoint, IDisposable).Dispose
  end if
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
  Dispose(True)
  GC.SuppressFinalize(Me)
End Sub
End Class
like image 97
dan radu Avatar answered May 22 '26 10:05

dan radu


If the relationship isn't defined in the interface: no, basically. Except maybe if A was a generic type (of T, for example), and T had multiple constraints, and the field was of type T. Not really appropriate in this case.

I would just do this by typing the field as the interesting type (IDataEndpoint), and handling the dispose as (in C# terms):

var disp = DataEndPoint as IDisposable;
if(disp != null) disp.Dispose();
like image 33
Marc Gravell Avatar answered May 22 '26 09:05

Marc Gravell