How to reflect all variables for an object?

N

Norton

Dear all,

I have created many objects
Currently i create a toString function, which is to list all variables value
inside this object
Somthing like

Public Class ABC
Dim sName as string = "Hello"
Dim iValue as integer = 10

Public Function ToString() as string
Dim temp as string
temp &= "sName =" & sName & ","
temp &= "iValue =" & iValue
Return temp
End Sub
End Class

Everytime i added a new variable i need to modify this function again
If there any method to list all variable name and its value in an object and
then return it as string?

Thx a lot
 
E

EricJ

If there any method to list all variable name and its value in an object
and
then return it as string?

I doubt you can do that, not to get the result you have now (if someone can
prove me wrong please do :) )
but I would like to suggest using a string builder instead of &

Dim sb As New System.Text.StringBuilder()
sb.Append("sName = ")
sb.Append(sName)
sb.Append(", iValue = ")
sb.Append(iValue.tostring)
return sb.tostring()

eric
 
J

Jay B. Harlow [MVP - Outlook]

Norton,
Everytime i added a new variable i need to modify this function again
If there any method to list all variable name and its value in an object and
then return it as string?
You mean other then the one you wrote?

No there is no built-in function that does that. However you could easily
build one that is based on Properties (as opposed to fields).

Something like:

Imports System.ComponentModel
Imports System.Text

Public Overrides Function ToString() As String
Dim list As PropertyDescriptorCollection =
TypeDescriptor.GetProperties(Me.GetType())
Dim sb As New StringBuilder
Dim delim As String
For Each item As PropertyDescriptor In list
sb.Append(delim)
sb.Append(item.Name)
sb.Append("=")
sb.Append(item.GetValue(Me))
delim = ","
Next
Return sb.ToString()
End Function


Using Reflection and the Type object returned from GetType you could
probably build one based on Fields almost as easily...

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top