Friday, May 16, 2008

generic property classes

Recently I needed an object that could compare the before and after values of fields and if there was a difference certain actions would be taken. This logic was soon applied to most of the fields in my class (business entity (BE)). This isn't feasible to continue for all BEs in the future. So I was trying to develop a way to create a single property that could meet the needs of any data type without having to recode the object for each datatype. After some searching I found a site that showed how to create a generic class. Not a class that uses a generic list, but an actual class that accepts a datatype when you instanciate it.

That little gem made the class easy to build and it was off to the races after that.
Example:

Imports System.Collections.Generic
'''
''' this is a generic class that can be used to contain properties for an object.
''' The class supports serialization. The class has before and current values and can tell if the vales are different.
'''

'''
'''
System.SerializableAttribute(), _
System.Diagnostics.DebuggerStepThroughAttribute(), _
System.ComponentModel.DesignerCategoryAttribute("code"), _
System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=True), _
System.Xml.Serialization.XmlRootAttribute([Namespace]:="", IsNullable:=False)> _
Public Class Generic_Property(Of T)

Private _B As T = Nothing
Private _V As T = Nothing

end class



notes: the objects inside the class get the type of 'T' and all references to the objects properties etc... use 'T' also.


example:
_
Public Property CV() As T
Get
Return _V
End Get
Set(ByVal value As T)
_V = value
End Set
End Property

notes: this example is serializable so it can be converted to xml and stored where ever. The values then convert back from xml to the class without any issue. It looks like all of the attributes for making the object serializable to xml are not displayed. If anyone needs help post a comment and I'll try to get you the code.

have fun.

~Lost

No comments: