Getting Property Values of an Object Dynamically in C#

Scenario

As I was working on a project I came across a need to do Exception Logging. Now, the requirement says to log not just the error, but also the query that was run during that error (while dealing with DB objects) and also the values that were ed for that specific Db Query.

Now, let's assume that we have a class as in the following:

employee class

So, to show the working currently, I will add the data to this class object by myself and then we will try to get the value of the objects thereafter.

I have another class where I want to do the exception logging when saving this Object to the DB.

The value is added to the Db as shown below:

code

Since it can be seen that we have called a method to save this Employee object in the DB.

In compliance with the purpose of this article, I will be making an attempt to create an exception in the definition of the method SaveEmpData(Employee emp).

The code for it will be as shown in the screenshot below:

SaveEmpData

As you can see, we have forced the program to create an exception and have called the LogException method in the Catch Block.

Let's go into the details of the LogException method. We have used the Reflection property of C# for this purpose and so we would need to include it in the solution by importing the System.Reflection and mentioning it in the .cs file as well.

The definition of the LogException method is as in the following:

LogException

As you can see, we have extracted each property of the object and then extracted the Property Name as well as its value to be used later.

The parameters used by the method are explained below:

  1. empObject: It is an object type parameter so it can have any value in it.

  2. Namespace: This had to be the Namespace+ObjectClassName that we would know when logging the error. For our specific case it will be “TestingObjectProperties_Console.Employee” since the Employee class is inside the TestingObjectProperties_Console namespace.

The output of the preceding program comes out to be as follows:

class

You can see that we got all the values in the preceding ouput. Although, you can get it in your required format.

I am also attaching the solution with it so as to provide a better understanding.
In case you need some more understanding regarding Reflection in C#, you can visit my other article “What Reflection in C# is”.

I hope this helped.

Thanks,
Vipul


Similar Articles