Sunday, November 2, 2008

Loop through properties of a .NET Class

You could use reflection to return all the public properties of a current class, such as the name and value of the property.

Sample Code:

Imports System.Web


Imports System.Reflection


Partial Class HCNLogin


Private Sub CreateHCNCookies(ByVal userID As Integer)


If Request.Browser.Cookies Then


Dim hcnUser As HCNUser = hcnUser.GetByID(userID)


If hcnUser IsNot Nothing Then


Dim t As Type = hcnUser.GetType()


For Each p As PropertyInfo In t.GetProperties()


If Not p.Name.Equals("ID") AndAlso Not p.Name.Equals("intUserID") Then


Response.Cookies(p.Name).Value = p.GetValue(hcnUser, Nothing)


Response.Cookies(p.Name).Expires = DateTime.Now.AddYears(10)


End If


Next


End If


End If


End Sub


End Class


Reference:
Loop through object properties?
blog comments powered by Disqus