StevenMcD
StevenMcD

Reputation: 17502

Compare objects in VB.NET

I want to write a function that accepts two objects as parameters and compare only the fields contained within the objects. I do not know what type the objects will be at design time, but the objects passed will be classes used within our application.

Is it possible to compare object's fields without knowing their types at runtime?

Upvotes: 5

Views: 18860

Answers (6)

Anas Musa
Anas Musa

Reputation: 11

I'm using the System.Reflection to compare my objects properties, and check if they're matching.

Public Function DoTheyMatch(Of T As New)(firstObject As T, secondObject As T) As Boolean
    Try
        If firstObject.GetType <> secondObject.GetType Then Return False
        For Each prop As PropertyInfo In firstObject.GetType().GetProperties()
            If prop Is Nothing OrElse prop.GetValue(firstObject) <> prop.GetValue(secondObject) Then
                Return False
            End If
        Next
        Return True
    Catch ex As Exception
        HandleException(ex)
    End Try
    Return False
End Function

and in order to call this function, you simply send your both objects as the following

Dim result as Boolean = DoTheyMatch(Obj1, Obj2)

Hope this finds your need.

Upvotes: 1

Sharif
Sharif

Reputation: 373

I recommend to use this NuGet package to compare objects: https://www.nuget.org/packages/CompareNETObjects/

here is it's source code: https://github.com/GregFinzer/Compare-Net-Objects

p.s. I'm not affiliated with it, but used in a couple projects.

Upvotes: 0

dbones
dbones

Reputation: 4504

If you do not want to write the reflection code, here is a library which includes an object comparison function:

AdapdevNet

Also, an article I wrote, Using Reflection to test for Equality, has the code in C#. You could convert this into VB.NET quite easily.

Upvotes: 1

Nathan
Nathan

Reputation: 2775

This function would compare two simple objects (_Objeto1 and _Objeto2). First, they must not be NOTHING. Second, they must be same type (_AnyObject.GetType.ToString). Third, we have to iterate through each of their properties and compare their values. If at least one property has a different value, the functions returns FALSE. Otherwise, it returns TRUE.

This function doesn't consider complex objects (one of their properties is another object). Simple objects are strings, integers, boolean, etc.

Imports System Imports Microsoft.VisualBasic Imports System.Reflection

Public Function CompararObjetos(ByVal _Objeto1 As Object, ByVal _Objeto2 As Object) As Boolean

    Dim _TipoObjeto1 As String = ""
    Dim _TipoObjeto2 As String = ""

    If Not _Objeto1 Is Nothing Then
        _TipoObjeto1 = _Objeto1.GetType.ToString
    End If

    If Not _Objeto2 Is Nothing Then
        _TipoObjeto2 = _Objeto2.GetType.ToString
    End If

    Dim _Resultado As Boolean = True

    If _TipoObjeto1 = _TipoObjeto2 Then
        Dim Propiedades() As PropertyInfo = _Objeto1.GetType.GetProperties
        Dim Propiedad As PropertyInfo
        Dim _Valor1 As Object
        Dim _Valor2 As Object
        For Each Propiedad In Propiedades
            _Valor1 = Propiedad.GetValue(_Objeto1, Nothing)
            _Valor2 = Propiedad.GetValue(_Objeto2, Nothing)
            If _Valor1 <> _Valor2 Then
                _Resultado = False
                Exit For
            End If
        Next
    Else
        _Resultado = False
    End If

    Return _Resultado

End Function

Upvotes: 0

Pondidum
Pondidum

Reputation: 11637

For this at work we have all our data access classes override GetHashCode: eg.

Public Overrides Function GetHashCode() As Integer
    Dim sb As New System.Text.StringBuilder

    sb.Append(_dateOfBirth)
    sb.Append(_notes)
    sb.Append(Name.LastName)
    sb.Append(Name.Preferred)
    sb.Append(Name.Title)
    sb.Append(Name.Forenames)

    Return sb.ToString.GetHashCode()

End Function

Then to compare two objects, you can say

Public Shared Function Compare(ByVal p1 As Person, ByVal p2 As Person) As Boolean

    Return p1.GetHashCode = p2.GetHashCode

End Function

Or more generically:

object1.GetHashCode = object2.GetHashCode

Upvotes: 2

Ryan
Ryan

Reputation: 8005

Yes, it is possible to find the fields, properties, and methods of objects at runtime. You will need to use System.Reflection and find the matching fields, make sure the datatypes are compatible, and then compare the values.

Upvotes: 8

Related Questions