views:

68

answers:

3

I'm trying to create a property that will allow the setting of a last name based on a variety of inputs. The code that calls this is parsing a name field. In some instances it will have a single last name, in others, a array of last names that need to be concatenated. I want to keep my concatenation code in a single place to make maintenance easier.

Here is my code, which of course doesn't work:

        Public Property LastName() As String
        Get
            Return _LastName
        End Get
        Set(ByVal value As String)
            _LastName = value
        End Set
    End Property

    Public WriteOnly Property LastName() As String()
        Set(ByVal value As String())
            For Each word As String In value
                _LastName &= word & " "
            Next

            _LastName = _LastName.Trim
        End Set
    End Property

I've tried numerous variations on this, even putting multiple Set in the same Property, but nothing seems to work. There must be some way to take in an array and a single instance value. The compiler clearly knows if the incoming object is an array or not.

I tried working with just a property of type String(), but then I can't return a String. The only solution that I can think of is differently named properties, which makes using the class more difficult, or a whole bunch of Subs and Functions overloading each other.

Suggestions?

Chris

+1  A: 

You cannot overload properties, so the property can by either a string or a string(), not both.

Consider having a different name for the string() property:

Public WriteOnly Property LastNameArray() As String()
    Set(ByVal value As String())
        For Each word As String In value
            _LastName &= word & " "
        Next

        _LastName = _LastName.Trim
    End Set
End Property
Oded
I was trying to avoid having to have a different name for the property for each of use reasons.
cjbarth
A: 

If your output is going to be of a different type than your input, then you cannot use a property for it. There is nothing wrong with using a function for it, good practice would say that you have the function name (LastName), and prepend a verb on to it (Get), so you end up with a function anme like GetLastName.

Public  Function GetLastName(ByVal names As String()) As String

(excuse my very rusty VB if there is something blatantly wrong)

slugster
A: 

What about something like this:

        Public Property LastName() As Object
        Get
            Return _LastName
        End Get
        Set(ByVal value As Object)
            If TypeOf (value) Is Array Then
                For Each word As String In value
                    _LastName &= word & " "
                Next

                _LastName = _LastName.Trim

            End If
            If TypeOf (value) Is String Then
                _LastName = value
            End If
        End Set
    End Property

Does anyone see a problem with this?

cjbarth