views:

59

answers:

2

Hi all I have the following code:

    Public Shared Function ConvertToString(ByVal list As IList) As String
        Dim strBuilder = New System.Text.StringBuilder()
        Dim item As Object
        For Each item In list
            strBuilder.Append(obj.ToString())
            strBuilder.Append(",")
        Next
        Return strBuilder.ToString(strBuilder.Length - 1)
    End Function

The intention is to convert an IList of custom objects to a string equivalent comprising each element in the Ilist. Unfortunately I can't seem to find a way to get the underlying data of the custom object, and of course as in the above example, using object simply gives me a string of types definitions, rather than access to the underlying data. Any assistance much appreciated.

Paul.

A: 

If you have control over the custom object you could override the ToString function to return the type of string data that you want to see.

I can't seem to find a way to get the underlying data of the custom object,

How come? What have you tried? You should be able to cast to the type or get it by reflection. Maybe you can show us a little more code?

Paul Sasik
+2  A: 

There's no default string representation of "the underlying data" in an object. It all depends on what you want to see. Say, for example, you have a Person class, and it has properties FirstName and LastName. You have an instance where FirstName = "John" and LastName = "Smith". What would the default representation of the underlying data be? "John Smith"? "Smith, John"? Something else?

That's (I assume) why .NET returns the type name in the ToString method if you haven't overridden that method to display something more useful. The framework has no way of knowing what would be a useful representation of the underlying data of any given class.

So I don't think you can make your method work for arbitrary classes. If you have a specific small set of classes you want this to work for, you can override ToString as Paul Sasik suggests to provide a useful string representation for them. Or, if you don't have access to the code for those classes, you could add an extension method for all of them, GetUnderlyingData or something like that, and call that extension method instead of ToString.

John M Gant
Thanks guys, the override worked. Can't think why I didn't think of this from the outset, obviously not enough caffein LOL.
Paul Johnson