0

I have a List(Of clsComponent).

It's declared as

Private _FilesToDownload As List(Of clsComponent)

I know how I can override ToString() for a class, but I don't know how I could override ToString() for a List(Of clsComponent).

Can anybody give me a hint how that could be done?

Thank you.

tmighty
  • 10,734
  • 21
  • 104
  • 218
  • You can't. The only way to override a member of a type is to declare your own type derived from the other type. You're not doing that so you can't override that or any other member. – jmcilhinney Nov 09 '17 at 10:45
  • Also, it's not clear what you're trying to achieve. What exactly would you expect the output to be and why do you feel you need an overridden `ToString` method to get it? – jmcilhinney Nov 09 '17 at 10:46
  • I would like to print out some properties of all clsComponent, all in one string. – tmighty Nov 09 '17 at 10:51
  • If you don't create your own custom list type, you may want to consider adding a new extension method to `IEnumerable(Of T)`. – Steven Doggart Nov 09 '17 at 10:57
  • Then your question should be along the lines of "How can I select a certain property from each item in a list?" – A Friend Nov 09 '17 at 10:57
  • Possible duplicate of [Overriding ToString() of List](https://stackoverflow.com/questions/1340128/overriding-tostring-of-listmyclass) – A Friend Nov 09 '17 at 11:00
  • Do you want to do this in just one place? If so then overriding a `ToString` method is pointless. You should only do that if it's going to be used in a significant number of places, particularly those where the `ToString` method is already called. If it's just one place then you should just call `Select` on your `List` and feed the result to `String.Join` or `String.Concat`. – jmcilhinney Nov 09 '17 at 11:05

1 Answers1

1

u can but u need Inherit list(of T)
and do override .toString Method there and after u can do what.
in this sample output is

Norbert,Adam,Eva,

List of All elements to string in one string

Sub TestThis()
    Dim Users As New AllUsers(Of User)
    Users.Add(New User With {.Name = "Norbert"})
    Users.Add(New User With {.Name = "Adam"})
    Users.Add(New User With {.Name = "Eva"})
    Debug.Print(Users.ToString)
End Sub

Public Class User
    Property Name As String
    Public Overrides Function ToString() As String
        Return Me.Name
    End Function
End Class
Public Class AllUsers(Of T)
    Inherits List(Of T)
    Public Overrides Function ToString() As String
        Dim Sb As New Text.StringBuilder
        For Each e In Me
            Sb.Append(e.ToString & ",")
        Next
        Return Sb.ToString
    End Function
End Class
  • Why write an entire class for something that can be accomplished with a single line of code with a standard `List(Of T)`? `Dim result = String.Join(",", users.Select(Function(s) s.Name).ToArray())` – Chris Dunaway Nov 13 '17 at 17:14