sebastiaan
sebastiaan

Reputation: 5917

How do I treat two similar types as one?

In VB.NET, I am trying to talk to a webservice (that can't be changed) to create and update customer data. The CreateCustomer service expects an object of type ConsumerPerson and the ChangeCustomer service expects an object of type ChangeData.

The properties of these two object are exactly the same, so I thought it would be wise to just set the properties using one single function.

However, I am unable to find a way to tell my function that I want to fill either the ConsumerPerson or the ChangeCustomer object.

How do I make this work without late binding problems?

Upvotes: 1

Views: 137

Answers (5)

Nescio
Nescio

Reputation: 28433

If you cannot change your objects, but they share the same field names, you could xml serialize the data and deserialize as the other class. - You should strongly consider the performance implications of this; however, it would give you the functionality you're asking for.

Upvotes: 0

JaredPar
JaredPar

Reputation: 755141

An interface sounds like your best approach. Here is a short code snippet. I picked a simple property named "Name" of type string. It should be easy to modify with the actual properties on your class.

Public Interface ICustomerData
  ReadOnly Property Name As String
End Interface

Public Class ConsumerPerson
  Implements ICustomerData

  Public ReadOnly Property Name As String Implements ICustomerData.Name
    Get
      return _name 
    End Get
  End Property
End Class

Public Class ChangeData
  Implements ICustomerData

  Public ReadOnly Property Name As String Implements ICustomerData.Name
    Get
      return _name 
    End Get
  End Property
End Class

Upvotes: 1

TheTXI
TheTXI

Reputation: 37905

Is it not possible to overload your function with the second data type?

Upvotes: 0

Dan Byström
Dan Byström

Reputation: 9244

You create an interface which both classes implements.

Upvotes: 1

Brann
Brann

Reputation: 32396

use an interface !

declare an interface IFoo, and implement its members in your subclasses ConsumerPerson and ChangeCustomer. That's exactly what interfaces are for.

Upvotes: 1

Related Questions