I’m trying to improve myself with generics but actually I dont know how to even start this task:
I need to build a method that will record two tables with logs. This method will recieve two objects of the same type and then I need them to be compared.
That the first table will be recorded with the name of the object.
The second table will receive the following data: the first table record ID, field name, old value and new value.
I need this to be build with generics since I have MANY different objects and I’m sure that’s going to be painful and weird to build any kind of switch case for each object that I want to record those information.
I hope you guys help me !
Unless these objects share a common interface you’ll have to use reflection to get the properties of an object, then loop through them and compare the values between objectA and objectB. Something like this:
You’ll have to have oldValue and newValue columns be set to varchar or nvarchar in the database and convert all property values to strings before saving, otherwise you can’t do what you are asking. Technically you wouldn’t even have to use generics here as both parameters could simply take an object and the reflection would still work AS LONG AS both objects were the same type. The generic parameter here just makes it a bit more clean and makes sure that the person calling this method can’t pass in two objects of different types accidently.
EDIT: To get the name of the object for your first table you would do: